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

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 

Recently uploaded (20)

Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 

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