SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
Android Concurrency
and beyond
novikov.ruslan@gmail.com
Why is concurrency in Android
important?
• Until pretty recently, real, concurrent
execution happened only on expensive server
hardware
• – Android already runs on multi-core devices.
• – It will get worse: Moore's law is now about
number, not speed, of CPUs
• – Android devices actually need to do multiple
things at the same time: Real Time Computing
Android Puts Concurrency
in your Face
• The UI is single threaded but will not tolerate
long running, synchronous tasks
• IPC (Binder) calls appear on non-UI threads
and you can't use the UI from a non-UI thread
(a topic for another day...)
Java Concurrency Primitives
• Language level constructs
– Synchronized
– Thread/Runnable
• Concurrency library (java.util.concurrent)
– Executor/Callable/Future
– Atomics
• All are available in Android
– Low level Java tools are really low level. If you find
yourself using them you might want to review your
architecture
• – Android Concurrency tools are firmly based on the
concurrency library (java.util.concurrent)
Java Memory Model
Compiler Optimizations
Is Vector Really so
Thread Safe?
Synchronized Collections
Concurrent Collections
• CopyOnWriteArrayList
• ConcurrentHashMap
• BlockingQueue
• Vector
• Hashtable
• Collections.synchronizedMap()
• …
Executor
• Executor
• ExecutorService
• ScheduledExecutorService
• Future
• Callable
• Executors
ExecutorService
Executor
Task submission:
executorService.submit(MyTask);
executorService.invokeAll(Collection<Tasks>);
executorService.invokeAny(Collection<Tasks>);
Lifecycle management:
executorService.shutdown();
executorService.shutdownNow();
Lifecycle observation:
executorService.isShutdown();
executorService.isTerminated();
executorService.awaitTermination();
Running
Shutting
Down
Terminated
shutdown()
Task / Execution Environment
Executor
Task:
Independent unit of work executed anywhere
Runnable
run()
Callable
call()
Execution Environment:
Technique used to execute the task
Executor
execute(Runnable)
Future future = executorService.submit(Callable);
Future
isDone()
isCancelled()
cancel()
Task manager/observer:
Threads on Android
UI
Android
App
Linux
Process
Native ThreadsJava Threads
BG BG BG
Android Scheduling
1. Foreground
2. Visible
3. Service
4. Background
Process level:
Android
App
Android Scheduling
1. Foreground
2. Visible
3. Service
4. Background
Process level:
App A
App A
Foreground Thread Group
Background Thread Group
App BApp B
> 90%
< 10%
Android Scheduling
1. Foreground
2. Visible
3. Service
4. Background
Process level:
App A
App A
Foreground Thread Group
Background Thread Group
App BApp B
> 90%
< 10%
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Activity Lifecycle
Time
Activity
Component
onCreate() onDestroy() onCreate() onDestroy()
Activity
Object
new() GC
Activity
Object
new() GC
Activity Lifecycle
Time
Activity
Component
onCreate() onDestroy() onCreate() onDestroy()
Activity
Object
new()
Activity
Object
new()
Start
BG
Reference
Goal
What technique shall I use for
my background thread
execution?
Android Asynchronous Techniques
• HandlerThread
• AsyncTask
• Service
• IntentService
• AsyncQueryHandler
• Loader
HandlerThread
• Inherits from Thread and encapsulates a
Looper-object
• Thread with a message queue and processing
loop
• Handles both Message and Runnable
Running Dead
t.quit()t = new HandlerThread().start();
How it works
HandlerThread
Handler
Thread
Create and Start
Add Process
Message Queue
1
23
t = new HandlerThread("BgThread");
t.start();
1
Handler h = new Handler(t.getLooper()) {
@Override
public void handleMessage(Message msg) {
//Process message
}
};
2
h.sendEmptyMessage(42);
3
Handler
HandlerThread
Runnable/Message submission:
Lifecycle management:
Runnable/Message removal:
removeCallbacks(Runnable);
removeMessages(Message)
post(Runnable);
postDelayed(Runnable);
postAtTime(Runnable)
postAtFrontOfQueue(Runnable);
sendMessage(Message);
sendMessageDelayed(Message);
sendMessageAtTime(Message);
sendMessageAtFrontOfQueue(Message);
AsyncTask
• Wraps Handler/Looper thread
communication.
• Utilizes the Executor framework.
• Callbacks for UI operations and Background
operation.
onCancelled()
4b
How it works
AsyncTask
UI
Thread
BG
Thread
new AsyncTask.execute()
1
onPreExecute()
2
3
doInBackground()
onPostExecute()
4a
AsyncTask.cancel()
Application Global Behavior
AsyncTask > Pitfalls
execute()
Queue Thread Pool
Activity
execute()Activity
execute()Service
execute()Receiver
execute()*
execute()
•Execution behavior has changed over time
AsyncTask > Pitfalls
execute()< Donut:
execute()< Honeycomb:
execute()
executeOnExecutor(Executor)
>= Honeycomb:
execute()
AsyncTask > Pitfalls
<uses-sdk android:targetSdkVersion="12" />
<uses-sdk android:targetSdkVersion="13" />
“So, if I call AsyncTask.execute on
Honeycomb and later my tasks will run
sequentially, right?”
“Right?!?”
“Eh, it depends…”
Possible solutions:
In reverse order of appeal
• Weak Reference
• Persistent
• Cancellable
• Independent
Weak Reference
• Just make all references to the Activity weak
• Currently a “well-known” solution
• The refuge of scoundrels:
– Allows the process to continue, even when the
value will be discarded
– Doesn't fix references to destroyed processes
• These are the folks who used to lazily initialize
their database connections.
Independent
• What happens when firing the AT is a contract
with the UI, and must complete?
• Do the simplest possible proxy to the model
• The inverse of the RESTful ContentProvider
cache
Service
Time
Activity
Component
onCreate() onDestroy() onCreate() onDestroy()
Service
Component
BG
onCreate() onDestroy()
Intent Service
Time
IntentService
Component
Intent 1BG Intent 2 Intent 3 Intent n
stopSelf()
onCreate() onDestroy()
Good Use Cases
• Serially executed tasks decoupled from other
component lifecycles.
• Off-load UI thread from BroadcastReceiver.
• REST client (ResultReceiver as callback)
IntentService
AsyncQueryHandler
• API Level 1
• Asynchronous operations on a
ContentResolver
• Query
• Insert
• Delete
• Update
• Wraps a HandlerThread
How it works
AsyncQueryHandler
UI
Thread
BG
Thread
new AsyncQueryHandler();
1
startQuery();
startInsert();
startUpdate();
startDelete();
2
onQueryComplete();
onInsertComplete();
onUpdateComplete();
onDeleteComplete();
3
DB
operations
Cons
• No cursor management
• No content observation
• No data retention on configuration changes
• Background thread can’t be forced to quit
AsyncQueryHandler
Loader
• API added in Honeycomb
• Available in compatibility package
• Load data in a background thread
• Observes data changes
• Retained on configuration changes
• Connected to the Activity and Fragment lifecycles
Basics
Loader
Data
Source
Loader
1 Load data in BG 2 Observe data
3 Lifecycle management 4 Retained on configuration change
Data Sources
Loader
Any Data
Source
Content
Provider
Custom
Loader
Cursor
Loader
How It Works
Loader
public class AndroidLoaderActivity extends ListActivity implements LoaderCallbacks<Cursor>{
SimpleCursorAdapter mAdapter;
public void onCreate(Bundle savedInstanceState) {
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(..., CONTENT_URI, ...);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
mAdapter.swapCursor(c);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
}
Used Material
• http://www.infoq.com/presentations/Concurrency-Android
• http://developer.android.com/reference/android/os/Proces
s.html
• http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-
133-faq.html
• http://docs.oracle.com/javase/specs/jls/se7/html/jls-
17.html
• https://plus.google.com/u/0/105051985738280261832/po
sts/XAZ4CeVP6DC
• https://github.com/keesj/gomo/wiki/AndroidScheduling
• http://stackoverflow.com/questions/7931032/android-
process-scheduling
• https://www.youtube.com/watch?v=_q12gb7OwsA
novikov.ruslan@gmail.com
Thanks
T
ha
n
ks

Weitere ähnliche Inhalte

Was ist angesagt?

Nakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishNakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - English
Svetlin Nakov
 
android activity
android activityandroid activity
android activity
Deepa Rani
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 

Was ist angesagt? (20)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Automotive android
Automotive androidAutomotive android
Automotive android
 
Introdução React.js
Introdução React.jsIntrodução React.js
Introdução React.js
 
Understaing Android EGL
Understaing Android EGLUnderstaing Android EGL
Understaing Android EGL
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Android with kotlin course
Android with kotlin courseAndroid with kotlin course
Android with kotlin course
 
새해 일어난 일
새해 일어난 일새해 일어난 일
새해 일어난 일
 
04 activities and activity life cycle
04 activities and activity life cycle04 activities and activity life cycle
04 activities and activity life cycle
 
Nakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - EnglishNakov - .NET Framework Overview - English
Nakov - .NET Framework Overview - English
 
Angular modules in depth
Angular modules in depthAngular modules in depth
Angular modules in depth
 
android activity
android activityandroid activity
android activity
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Job schedulers android
Job schedulers androidJob schedulers android
Job schedulers android
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Django Interview Questions and Answers
Django Interview Questions and AnswersDjango Interview Questions and Answers
Django Interview Questions and Answers
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Overlapped IO와 IOCP 조사 발표
Overlapped IO와 IOCP 조사 발표Overlapped IO와 IOCP 조사 발표
Overlapped IO와 IOCP 조사 발표
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Android activities & views
Android activities & viewsAndroid activities & views
Android activities & views
 

Andere mochten auch

Andere mochten auch (7)

Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
RxJava on Android
RxJava on AndroidRxJava on Android
RxJava on Android
 
RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015RxJava for Android - GDG DevFest Ukraine 2015
RxJava for Android - GDG DevFest Ukraine 2015
 
Rx Java architecture
Rx Java architectureRx Java architecture
Rx Java architecture
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Operating Systems - File Management
Operating Systems -  File ManagementOperating Systems -  File Management
Operating Systems - File Management
 

Ähnlich wie Android concurrency

l1-reactnativeintroduction-160816150540.pdf
l1-reactnativeintroduction-160816150540.pdfl1-reactnativeintroduction-160816150540.pdf
l1-reactnativeintroduction-160816150540.pdf
Hương Trà Pé Xjnk
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
Muhammad Sajid
 

Ähnlich wie Android concurrency (20)

Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Real time web
Real time webReal time web
Real time web
 
Angular meetup 2 2019-08-29
Angular meetup 2   2019-08-29Angular meetup 2   2019-08-29
Angular meetup 2 2019-08-29
 
Android Whats running in background
Android Whats running in backgroundAndroid Whats running in background
Android Whats running in background
 
l1-reactnativeintroduction-160816150540.pdf
l1-reactnativeintroduction-160816150540.pdfl1-reactnativeintroduction-160816150540.pdf
l1-reactnativeintroduction-160816150540.pdf
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Web Performance & Latest in React
Web Performance & Latest in ReactWeb Performance & Latest in React
Web Performance & Latest in React
 
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
"You Don't Know NODE.JS" by Hengki Mardongan Sihombing (Urbanhire)
 
Node.js for beginner
Node.js for beginnerNode.js for beginner
Node.js for beginner
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
 
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScriptReact Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
 
PUG Challenge 2016 - The nativescript pug app challenge
PUG Challenge 2016 -  The nativescript pug app challengePUG Challenge 2016 -  The nativescript pug app challenge
PUG Challenge 2016 - The nativescript pug app challenge
 
Griffon for the Enterprise
Griffon for the EnterpriseGriffon for the Enterprise
Griffon for the Enterprise
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
All about that reactive ui
All about that reactive uiAll about that reactive ui
All about that reactive ui
 
Asynchronous Programming in Android
Asynchronous Programming in AndroidAsynchronous Programming in Android
Asynchronous Programming in Android
 
Angular Meetup 1 - Angular Basics and Workshop
Angular Meetup 1 - Angular Basics and WorkshopAngular Meetup 1 - Angular Basics and Workshop
Angular Meetup 1 - Angular Basics and Workshop
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 

Kürzlich hochgeladen

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Kürzlich hochgeladen (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

Android concurrency