SlideShare a Scribd company logo
1 of 22
Download to read offline
Copyright © 2013 CommonsWare, LLC
Painless
Threading
Apps World Europe 2013
Copyright © 2013 CommonsWare, LLC
Painless
Threading
Apps World Europe 2013
Not Quite As Painful
Copyright © 2013 CommonsWare, LLC
Problem #1: Jank
● Sluggish UI Response to User Input
– Example: hiccups while scrolling a list
● Reason:Too MuchTime Spent on Main
ApplicationThread
– 60 fps UI updates 16 ms/frame need to→ →
spend < 1ms per callback method
● Limitation: Cannot Modify UI from
BackgroundThread
Copyright © 2013 CommonsWare, LLC
Problem #2: Changes
● Configuration Changes
– Example: rotate the device
● Default Behavior = Destroy/Recreate UI
– Activities and (most) fragments
● WhatWe Do NotWant: Lost Results
– Spin off a thread, which updates the former UI,
not the current UI
Copyright © 2013 CommonsWare, LLC
Problem #3: Sleep
● Devices Fall Asleep After Inactivity
– Screen goes dark, CPU powers down
– Can be in as little as 15 seconds
● Less if user presses POWER button directly
● WhatWe Do NotWant: IncompleteWork
– Spin off thread to do network I/O, fall asleep
mid-conversation, with messed up results
Copyright © 2013 CommonsWare, LLC
Problem #4: Cores
● Good News!We Have Multiple Cores Now!
– Better responsiveness from CPU-intensive apps,
such as games
● Bad News!We Have Multiple Cores Now!
– Thread safety now a bigger problem than before
– Can have results ranging from outright crashes
to subtle inconsistencies
Copyright © 2013 CommonsWare, LLC
Timing Is Everything
● GeneralTransactional Recipe
– 1 ms to 1 s use→ AsyncTask and retained
fragment
– 1-15 s use→ IntentService and event bus
– 15+ s use wakeful pattern and event bus→
● Also if the work is triggered outside the UI, such as
via a push message
Copyright © 2013 CommonsWare, LLC
AsyncTask
● QuickWork
– Disk and database I/O
– Trivial network I/O (e.g., downloading
thumbnails)
● Android SuppliesThread Pool
● Android GivesYou Hook to Send Results to
Main ApplicationThread
Copyright © 2013 CommonsWare, LLC
SimpleAsyncTask
● https://gist.github.com/commonsguy/6900714
● AsyncTask Subclass, Simpler API
– Override doInBackground() and do the work that will
take a moment
● Called on a framework-supplied background thread
– Override onPostExecute() and update the UI based
on the background work
● Called on main application thread once doInBackground()
completes
– Create instance, call execute()
Copyright © 2013 CommonsWare, LLC
AsyncTask
● What AsyncTask Itself GivesYou
– Optional parameters from execute() to
doInBackground()
– Optional results from doInBackground()
passed to onPostExecute()
– Additional hooks, like onPublishProgress()
– Thread pool choices
● Cost: a bit of complexity
Copyright © 2013 CommonsWare, LLC
Retained Fragment
● setRetainInstance(true)
● Effects
– Fragment not destroyed and recreated on
configuration change
– onPostExecute() can work with fragment to
update UI, will affect the appropriate widgets
depending on timing
Copyright © 2013 CommonsWare, LLC
Limits of AsyncTask
● Does Not Keep Device Awake
● Does Not Keep Process Alive
● Still Must Deal withThread Safety
Copyright © 2013 CommonsWare, LLC
IntentService
● Use Case
– Work that needs to be completed even if user
leaves your UI (e.g., presses HOME)...
– ...but not so long that the device is likely to fall
asleep while you are doing that work
● Benefits
– Lets Android know that you are doing work
– Immune to configuration changes
Copyright © 2013 CommonsWare, LLC
IntentService Recipe
● Extend IntentService
– Override onHandleIntent(), where you do
work on framework-supplied background thread
● Add <service> to Manifest
● Call startService() toTriggerWork
– Takes Intent to identify the service
– Package extras on Intent for work details
– Intent supplied to onHandleIntent()
Copyright © 2013 CommonsWare, LLC
Event Bus
● Loose Coupling for Result Delivery
– LocalBroadcastManager
● Part of Android Support package
– greenrobot's EventBus
– Square's Otto
● Not as thread-savvy and so may not be suitable
Copyright © 2013 CommonsWare, LLC
Event Bus Recipe
● UI Layer Receives Events
– Register in onResume(), unregister in
onPause()
● IntentService Sends Events
– Picked up by UI layer if in foreground, to do
what's needed
– If not picked up, detect and raise a
Notification, if appropriate
Copyright © 2013 CommonsWare, LLC
Limits of IntentService
● No Direct UI Access
– Message-based for work requests and results
● Does Not Keep Device Awake
● Still Must Deal withThread Safety
– IntentService itself is single-threaded, so multiple
commands are not a problem
– ...but may still have other code accessing same data on
main application thread, other threads
Copyright © 2013 CommonsWare, LLC
WakefulIntentService
● http://github.com/commonsguy/cwac-wakeful
● Keeps Device Awake DuringWork
● Recipe
– Download JAR
– Extend WakefulIntentService instead of
IntentService
– Override doWakefulWork() instead of
onHandleIntent()
– Trigger work via sendWakefulWork()
Copyright © 2013 CommonsWare, LLC
WakefulBroadcastReceiver
● Alternative to WakefulIntentService
– Ships with Android Support package
● Recipe
– Have work be triggered by broadcast to a subclass of
WakefulBroadcastReceiver
– Use startWakefulService() in onReceive()
– IntentService calls completeWakefulIntent()
when work done
Copyright © 2013 CommonsWare, LLC
Limits ofWakeful Approaches
● No Direct UI Access
– Still using event bus for delivering results
● Still Must Deal withThread Safety
● Power Consumption
– Require WAKE_LOCK permission
– You may appear in “battery blame screen” in
Settings
Copyright © 2013 CommonsWare, LLC
Recap
● GeneralTransactional Recipe
– 1 ms to 1 s use→ AsyncTask and retained
fragment
– 1-15 s use→ IntentService and event bus
– 15+ s use wakeful pattern and event bus→
● Also if the work is triggered outside the UI, such as
via a push message
Copyright © 2013 CommonsWare, LLC
Code!
● https://github.com/commonsguy/cw-omnibus
● SimpleAsyncTask/Retained Fragment
– /Threads/SimpleAsyncTask
● AsyncTask/Retained Fragment
– /Threads/AsyncTask
● WakefulIntentService/Event Bus
– /EventBus

More Related Content

What's hot

High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010Nicholas Zakas
 
Building Cross Platform Apps with Electron
Building Cross Platform Apps with ElectronBuilding Cross Platform Apps with Electron
Building Cross Platform Apps with ElectronChris Ward
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work managerlpu
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)Nicholas Zakas
 
Develop Desktop Apps with Electron
Develop Desktop Apps with ElectronDevelop Desktop Apps with Electron
Develop Desktop Apps with ElectronEueung Mulyana
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)Nicholas Zakas
 
Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...
Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...
Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...Nicholas Jansma
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!Nicholas Zakas
 

What's hot (9)

High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010
 
Building Cross Platform Apps with Electron
Building Cross Platform Apps with ElectronBuilding Cross Platform Apps with Electron
Building Cross Platform Apps with Electron
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work manager
 
YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
 
Develop Desktop Apps with Electron
Develop Desktop Apps with ElectronDevelop Desktop Apps with Electron
Develop Desktop Apps with Electron
 
High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)
 
Measuring Continuity
Measuring ContinuityMeasuring Continuity
Measuring Continuity
 
Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...
Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...
Make It Fast - Using Modern Browser Performance APIs to Monitor and Improve t...
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
 

Similar to Not Quite As Painful Threading

Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operationMatteo Bonifazi
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2Dori Waldman
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2Paramvir Singh
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle瑋琮 林
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _courseDori Waldman
 
2013-05-15 threads. why and how
2013-05-15 threads. why and how2013-05-15 threads. why and how
2013-05-15 threads. why and howCocoaHeads Tricity
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8Utkarsh Mankad
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work managerbhatnagar.gaurav83
 
The hourly network outage - Booking.com.pdf
The hourly network outage - Booking.com.pdfThe hourly network outage - Booking.com.pdf
The hourly network outage - Booking.com.pdfSiteReliabilityEngin
 
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAndroid Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAnuradha Weeraman
 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...DroidConTLV
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragmentsVitali Pekelis
 
Improving MeeGo boot-up time
Improving MeeGo boot-up timeImproving MeeGo boot-up time
Improving MeeGo boot-up timeHiroshi Doyu
 
2012 04-19 theory-of_operation
2012 04-19 theory-of_operation2012 04-19 theory-of_operation
2012 04-19 theory-of_operationbobwolff68
 
Apple watch deck yodel meetup 4-16
Apple watch deck  yodel meetup 4-16Apple watch deck  yodel meetup 4-16
Apple watch deck yodel meetup 4-16Shirin Sabahi
 
"13 ways to run web applications on the Internet" Andrii Shumada
"13 ways to run web applications on the Internet" Andrii Shumada"13 ways to run web applications on the Internet" Andrii Shumada
"13 ways to run web applications on the Internet" Andrii ShumadaFwdays
 
Background threads, async communication and vaadin
Background threads, async communication and vaadinBackground threads, async communication and vaadin
Background threads, async communication and vaadinPetter Holmström
 
Vuejs getting-started - Extended Version
Vuejs getting-started - Extended VersionVuejs getting-started - Extended Version
Vuejs getting-started - Extended VersionMurat Doğan
 

Similar to Not Quite As Painful Threading (20)

Android - Background operation
Android - Background operationAndroid - Background operation
Android - Background operation
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
 
Android Connecting to internet Part 2
Android  Connecting to internet Part 2Android  Connecting to internet Part 2
Android Connecting to internet Part 2
 
Android life cycle
Android life cycleAndroid life cycle
Android life cycle
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
 
2013-05-15 threads. why and how
2013-05-15 threads. why and how2013-05-15 threads. why and how
2013-05-15 threads. why and how
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
 
Analysing in depth work manager
Analysing in depth work managerAnalysing in depth work manager
Analysing in depth work manager
 
The hourly network outage - Booking.com.pdf
The hourly network outage - Booking.com.pdfThe hourly network outage - Booking.com.pdf
The hourly network outage - Booking.com.pdf
 
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the TrenchesAndroid Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the Trenches
 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
 
Lecture #4 activities &amp; fragments
Lecture #4  activities &amp; fragmentsLecture #4  activities &amp; fragments
Lecture #4 activities &amp; fragments
 
Improving MeeGo boot-up time
Improving MeeGo boot-up timeImproving MeeGo boot-up time
Improving MeeGo boot-up time
 
2012 04-19 theory-of_operation
2012 04-19 theory-of_operation2012 04-19 theory-of_operation
2012 04-19 theory-of_operation
 
PureMVC
PureMVCPureMVC
PureMVC
 
Apple watch deck yodel meetup 4-16
Apple watch deck  yodel meetup 4-16Apple watch deck  yodel meetup 4-16
Apple watch deck yodel meetup 4-16
 
"13 ways to run web applications on the Internet" Andrii Shumada
"13 ways to run web applications on the Internet" Andrii Shumada"13 ways to run web applications on the Internet" Andrii Shumada
"13 ways to run web applications on the Internet" Andrii Shumada
 
Background threads, async communication and vaadin
Background threads, async communication and vaadinBackground threads, async communication and vaadin
Background threads, async communication and vaadin
 
Vuejs getting-started - Extended Version
Vuejs getting-started - Extended VersionVuejs getting-started - Extended Version
Vuejs getting-started - Extended Version
 

More from CommonsWare

Gradle and Your Android Wearable Projects
Gradle and Your Android Wearable ProjectsGradle and Your Android Wearable Projects
Gradle and Your Android Wearable ProjectsCommonsWare
 
Getting Android Developers for Your Wearables
Getting Android Developers for Your WearablesGetting Android Developers for Your Wearables
Getting Android Developers for Your WearablesCommonsWare
 
When Microwatts Are Precious: Battery Tips for Wearable Apps
When Microwatts Are Precious: Battery Tips for Wearable AppsWhen Microwatts Are Precious: Battery Tips for Wearable Apps
When Microwatts Are Precious: Battery Tips for Wearable AppsCommonsWare
 
The Action Bar: Front to Back
The Action Bar: Front to BackThe Action Bar: Front to Back
The Action Bar: Front to BackCommonsWare
 
Android Security: Defending Your Users
Android Security: Defending Your UsersAndroid Security: Defending Your Users
Android Security: Defending Your UsersCommonsWare
 
Secondary Screen Support Using DisplayManager
Secondary Screen Support Using DisplayManagerSecondary Screen Support Using DisplayManager
Secondary Screen Support Using DisplayManagerCommonsWare
 
Mastering the Master Detail Pattern
Mastering the Master Detail PatternMastering the Master Detail Pattern
Mastering the Master Detail PatternCommonsWare
 
Android Development: The 20,000-Foot View
Android Development: The 20,000-Foot ViewAndroid Development: The 20,000-Foot View
Android Development: The 20,000-Foot ViewCommonsWare
 
Maps V2... And You!
Maps V2... And You!Maps V2... And You!
Maps V2... And You!CommonsWare
 
A Deep Dive Into ViewPager
A Deep Dive Into ViewPagerA Deep Dive Into ViewPager
A Deep Dive Into ViewPagerCommonsWare
 
Second-Screen Support in Android 4.2
Second-Screen Support in Android 4.2Second-Screen Support in Android 4.2
Second-Screen Support in Android 4.2CommonsWare
 
Integrate Android Apps and Web Apps
Integrate Android Apps and Web AppsIntegrate Android Apps and Web Apps
Integrate Android Apps and Web AppsCommonsWare
 
From Android to the Mobile Web
From Android to the Mobile WebFrom Android to the Mobile Web
From Android to the Mobile WebCommonsWare
 
The Wonderful World of Wearables
The Wonderful World of WearablesThe Wonderful World of Wearables
The Wonderful World of WearablesCommonsWare
 
Securing User Data with SQLCipher
Securing User Data with SQLCipherSecuring User Data with SQLCipher
Securing User Data with SQLCipherCommonsWare
 
Beaming Data to Devices with NFC
Beaming Data to Devices with NFCBeaming Data to Devices with NFC
Beaming Data to Devices with NFCCommonsWare
 
What's New in Jelly Bean
What's New in Jelly BeanWhat's New in Jelly Bean
What's New in Jelly BeanCommonsWare
 
Making Money at Mobile: 60 Business Models
Making Money at Mobile: 60 Business ModelsMaking Money at Mobile: 60 Business Models
Making Money at Mobile: 60 Business ModelsCommonsWare
 
AppsWorld Keynote
AppsWorld KeynoteAppsWorld Keynote
AppsWorld KeynoteCommonsWare
 

More from CommonsWare (20)

Gradle and Your Android Wearable Projects
Gradle and Your Android Wearable ProjectsGradle and Your Android Wearable Projects
Gradle and Your Android Wearable Projects
 
Getting Android Developers for Your Wearables
Getting Android Developers for Your WearablesGetting Android Developers for Your Wearables
Getting Android Developers for Your Wearables
 
When Microwatts Are Precious: Battery Tips for Wearable Apps
When Microwatts Are Precious: Battery Tips for Wearable AppsWhen Microwatts Are Precious: Battery Tips for Wearable Apps
When Microwatts Are Precious: Battery Tips for Wearable Apps
 
The Action Bar: Front to Back
The Action Bar: Front to BackThe Action Bar: Front to Back
The Action Bar: Front to Back
 
Android Security: Defending Your Users
Android Security: Defending Your UsersAndroid Security: Defending Your Users
Android Security: Defending Your Users
 
Secondary Screen Support Using DisplayManager
Secondary Screen Support Using DisplayManagerSecondary Screen Support Using DisplayManager
Secondary Screen Support Using DisplayManager
 
Mastering the Master Detail Pattern
Mastering the Master Detail PatternMastering the Master Detail Pattern
Mastering the Master Detail Pattern
 
Android Development: The 20,000-Foot View
Android Development: The 20,000-Foot ViewAndroid Development: The 20,000-Foot View
Android Development: The 20,000-Foot View
 
Maps V2... And You!
Maps V2... And You!Maps V2... And You!
Maps V2... And You!
 
A Deep Dive Into ViewPager
A Deep Dive Into ViewPagerA Deep Dive Into ViewPager
A Deep Dive Into ViewPager
 
Second-Screen Support in Android 4.2
Second-Screen Support in Android 4.2Second-Screen Support in Android 4.2
Second-Screen Support in Android 4.2
 
Integrate Android Apps and Web Apps
Integrate Android Apps and Web AppsIntegrate Android Apps and Web Apps
Integrate Android Apps and Web Apps
 
From Android to the Mobile Web
From Android to the Mobile WebFrom Android to the Mobile Web
From Android to the Mobile Web
 
X Means Y
X Means YX Means Y
X Means Y
 
The Wonderful World of Wearables
The Wonderful World of WearablesThe Wonderful World of Wearables
The Wonderful World of Wearables
 
Securing User Data with SQLCipher
Securing User Data with SQLCipherSecuring User Data with SQLCipher
Securing User Data with SQLCipher
 
Beaming Data to Devices with NFC
Beaming Data to Devices with NFCBeaming Data to Devices with NFC
Beaming Data to Devices with NFC
 
What's New in Jelly Bean
What's New in Jelly BeanWhat's New in Jelly Bean
What's New in Jelly Bean
 
Making Money at Mobile: 60 Business Models
Making Money at Mobile: 60 Business ModelsMaking Money at Mobile: 60 Business Models
Making Money at Mobile: 60 Business Models
 
AppsWorld Keynote
AppsWorld KeynoteAppsWorld Keynote
AppsWorld Keynote
 

Recently uploaded

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Not Quite As Painful Threading

  • 1. Copyright © 2013 CommonsWare, LLC Painless Threading Apps World Europe 2013
  • 2. Copyright © 2013 CommonsWare, LLC Painless Threading Apps World Europe 2013 Not Quite As Painful
  • 3. Copyright © 2013 CommonsWare, LLC Problem #1: Jank ● Sluggish UI Response to User Input – Example: hiccups while scrolling a list ● Reason:Too MuchTime Spent on Main ApplicationThread – 60 fps UI updates 16 ms/frame need to→ → spend < 1ms per callback method ● Limitation: Cannot Modify UI from BackgroundThread
  • 4. Copyright © 2013 CommonsWare, LLC Problem #2: Changes ● Configuration Changes – Example: rotate the device ● Default Behavior = Destroy/Recreate UI – Activities and (most) fragments ● WhatWe Do NotWant: Lost Results – Spin off a thread, which updates the former UI, not the current UI
  • 5. Copyright © 2013 CommonsWare, LLC Problem #3: Sleep ● Devices Fall Asleep After Inactivity – Screen goes dark, CPU powers down – Can be in as little as 15 seconds ● Less if user presses POWER button directly ● WhatWe Do NotWant: IncompleteWork – Spin off thread to do network I/O, fall asleep mid-conversation, with messed up results
  • 6. Copyright © 2013 CommonsWare, LLC Problem #4: Cores ● Good News!We Have Multiple Cores Now! – Better responsiveness from CPU-intensive apps, such as games ● Bad News!We Have Multiple Cores Now! – Thread safety now a bigger problem than before – Can have results ranging from outright crashes to subtle inconsistencies
  • 7. Copyright © 2013 CommonsWare, LLC Timing Is Everything ● GeneralTransactional Recipe – 1 ms to 1 s use→ AsyncTask and retained fragment – 1-15 s use→ IntentService and event bus – 15+ s use wakeful pattern and event bus→ ● Also if the work is triggered outside the UI, such as via a push message
  • 8. Copyright © 2013 CommonsWare, LLC AsyncTask ● QuickWork – Disk and database I/O – Trivial network I/O (e.g., downloading thumbnails) ● Android SuppliesThread Pool ● Android GivesYou Hook to Send Results to Main ApplicationThread
  • 9. Copyright © 2013 CommonsWare, LLC SimpleAsyncTask ● https://gist.github.com/commonsguy/6900714 ● AsyncTask Subclass, Simpler API – Override doInBackground() and do the work that will take a moment ● Called on a framework-supplied background thread – Override onPostExecute() and update the UI based on the background work ● Called on main application thread once doInBackground() completes – Create instance, call execute()
  • 10. Copyright © 2013 CommonsWare, LLC AsyncTask ● What AsyncTask Itself GivesYou – Optional parameters from execute() to doInBackground() – Optional results from doInBackground() passed to onPostExecute() – Additional hooks, like onPublishProgress() – Thread pool choices ● Cost: a bit of complexity
  • 11. Copyright © 2013 CommonsWare, LLC Retained Fragment ● setRetainInstance(true) ● Effects – Fragment not destroyed and recreated on configuration change – onPostExecute() can work with fragment to update UI, will affect the appropriate widgets depending on timing
  • 12. Copyright © 2013 CommonsWare, LLC Limits of AsyncTask ● Does Not Keep Device Awake ● Does Not Keep Process Alive ● Still Must Deal withThread Safety
  • 13. Copyright © 2013 CommonsWare, LLC IntentService ● Use Case – Work that needs to be completed even if user leaves your UI (e.g., presses HOME)... – ...but not so long that the device is likely to fall asleep while you are doing that work ● Benefits – Lets Android know that you are doing work – Immune to configuration changes
  • 14. Copyright © 2013 CommonsWare, LLC IntentService Recipe ● Extend IntentService – Override onHandleIntent(), where you do work on framework-supplied background thread ● Add <service> to Manifest ● Call startService() toTriggerWork – Takes Intent to identify the service – Package extras on Intent for work details – Intent supplied to onHandleIntent()
  • 15. Copyright © 2013 CommonsWare, LLC Event Bus ● Loose Coupling for Result Delivery – LocalBroadcastManager ● Part of Android Support package – greenrobot's EventBus – Square's Otto ● Not as thread-savvy and so may not be suitable
  • 16. Copyright © 2013 CommonsWare, LLC Event Bus Recipe ● UI Layer Receives Events – Register in onResume(), unregister in onPause() ● IntentService Sends Events – Picked up by UI layer if in foreground, to do what's needed – If not picked up, detect and raise a Notification, if appropriate
  • 17. Copyright © 2013 CommonsWare, LLC Limits of IntentService ● No Direct UI Access – Message-based for work requests and results ● Does Not Keep Device Awake ● Still Must Deal withThread Safety – IntentService itself is single-threaded, so multiple commands are not a problem – ...but may still have other code accessing same data on main application thread, other threads
  • 18. Copyright © 2013 CommonsWare, LLC WakefulIntentService ● http://github.com/commonsguy/cwac-wakeful ● Keeps Device Awake DuringWork ● Recipe – Download JAR – Extend WakefulIntentService instead of IntentService – Override doWakefulWork() instead of onHandleIntent() – Trigger work via sendWakefulWork()
  • 19. Copyright © 2013 CommonsWare, LLC WakefulBroadcastReceiver ● Alternative to WakefulIntentService – Ships with Android Support package ● Recipe – Have work be triggered by broadcast to a subclass of WakefulBroadcastReceiver – Use startWakefulService() in onReceive() – IntentService calls completeWakefulIntent() when work done
  • 20. Copyright © 2013 CommonsWare, LLC Limits ofWakeful Approaches ● No Direct UI Access – Still using event bus for delivering results ● Still Must Deal withThread Safety ● Power Consumption – Require WAKE_LOCK permission – You may appear in “battery blame screen” in Settings
  • 21. Copyright © 2013 CommonsWare, LLC Recap ● GeneralTransactional Recipe – 1 ms to 1 s use→ AsyncTask and retained fragment – 1-15 s use→ IntentService and event bus – 15+ s use wakeful pattern and event bus→ ● Also if the work is triggered outside the UI, such as via a push message
  • 22. Copyright © 2013 CommonsWare, LLC Code! ● https://github.com/commonsguy/cw-omnibus ● SimpleAsyncTask/Retained Fragment – /Threads/SimpleAsyncTask ● AsyncTask/Retained Fragment – /Threads/AsyncTask ● WakefulIntentService/Event Bus – /EventBus