android concurrency & synchronization: part 6schmidt/cs282/pdfs/concurrency-and... · android...
TRANSCRIPT
![Page 1: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/1.jpg)
Android Concurrency & Synchronization: Part 6
Douglas C. Schmidt
[email protected] www.dre.vanderbilt.edu/~schmidt
Institute for Software Integrated Systems
Vanderbilt University Nashville, Tennessee, USA
CS 282 Principles of Operating Systems II Systems Programming for Android
![Page 2: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/2.jpg)
Android Concurrency & Synchronization D. C. Schmidt
2
Async Task
Learning Objectives in this Part of the Module • Understand Android concurrency
idioms & associated programming mechanisms
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B
![Page 3: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/3.jpg)
Android Concurrency & Synchronization D. C. Schmidt
3
• Android’s UI has several design constraints • An “Application Not Responding”
(ANR) dialog is generated if app’s UI Thread doesn’t respond to user input within a short time
See developer.android.com/training/articles/perf-anr.html for more on ANRs
Motivating Android Concurrency Idioms
![Page 4: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/4.jpg)
Android Concurrency & Synchronization D. C. Schmidt
4
• Android’s UI has several design constraints • An “Application Not Responding”
(ANR) dialog is generated if app’s UI Thread doesn’t respond to user input within a short time
• Non-UI Threads can’t access widgets in the UI toolkit since it’s not thread-safe
android-developers.blogspot.com/2009/05/painless-threading.html has more
Motivating Android Concurrency Idioms
![Page 5: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/5.jpg)
Android Concurrency & Synchronization D. C. Schmidt
5
Motivating Android Concurrency Idioms • Android’s UI has several design
constraints • Android therefore supports various
concurrency idioms for processing long-running operations in background thread(s) & communicating with the UI Thread
Loop
er Message
Message
Message
Message
Message
Message Queue
Message
UI Thread (main thread)
See developer.android.com/training/multiple-threads/communicate-ui.html
![Page 6: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/6.jpg)
Android Concurrency & Synchronization D. C. Schmidt
6
Motivating Android Concurrency Idioms • Android’s UI has several design
constraints • Android therefore supports various
concurrency idioms for processing long-running operations in background thread(s) & communicating with the UI Thread • Handlers, Messages, &
Runnables • Allows an app to spawn threads
that perform background operations & publish results on the UI thread
Loop
er Message
Message
Message
Message
Message
Message Queue
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B
UI Thread (main thread)
www.vogella.com/articles/AndroidBackgroundProcessing/article.html has more
![Page 7: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/7.jpg)
Android Concurrency & Synchronization D. C. Schmidt
7
Async Task
Motivating Android Concurrency Idioms • Android’s UI has several design
constraints • Android therefore supports various
concurrency idioms for processing long-running operations in background thread(s) & communicating with the UI Thread • Handlers, Messages, &
Runnables • AsyncTask
• Allow an app to run background operations & publish results on the UI thread without manipulating threads or handlers
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B
www.vogella.com/articles/AndroidBackgroundProcessing/article.html has more
![Page 8: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/8.jpg)
Android Concurrency & Synchronization D. C. Schmidt
8
The Android Looper Class • A Looper provides a message
queue to a thread • Only one Looper is allowed
per Thread
developer.android.com/reference/android/os/Looper.html has more info
Loop
er Message
Message
Message
Message
Message
Message Queue
Thread
Message
The UI Thread has a Looper, but Loopers can also be used in
non-UI threads
![Page 9: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/9.jpg)
Android Concurrency & Synchronization D. C. Schmidt
9
The Android Looper Class • A Looper provides a message
queue to a thread • Only one Looper is allowed
per Thread • The Looper.loop() method runs
a Thread’s main event loop, which waits for Messages & dispatches them to their Handlers
public class Looper { ... final MessageQueue mQueue; public static void loop() { ... for (;;) { Message msg = queue.next(); ... msg.target. dispatchMessage(msg); ... } ...
![Page 10: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/10.jpg)
Android Concurrency & Synchronization D. C. Schmidt
10
The Android Looper Class • A Looper provides a message
queue to a thread • Only one Looper is allowed
per Thread • The Looper.loop() method runs
a Thread’s main event loop, which waits for Messages & dispatches them to their Handlers
public class Looper { ... final MessageQueue mQueue; public static void loop() { ... for (;;) { Message msg = queue.next(); ... msg.target. dispatchMessage(msg); ... } ...
This call can block
![Page 11: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/11.jpg)
Android Concurrency & Synchronization D. C. Schmidt
11
The Android Looper Class • A Looper provides a message
queue to a thread • Only one Looper is allowed
per Thread • The Looper.loop() method runs
a Thread’s main event loop, which waits for Messages & dispatches them to their Handlers
public class Looper { ... final MessageQueue mQueue; public static void loop() { ... for (;;) { Message msg = queue.next(); ... msg.target. dispatchMessage(msg); ... } ... Note inversion of control
![Page 12: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/12.jpg)
Android Concurrency & Synchronization D. C. Schmidt
12
The Android Looper Class • A Looper provides a message
queue to a thread • Only one Looper is allowed
per Thread • The Looper.loop() method runs
a Thread’s main event loop, which waits for Messages & dispatches them to their Handlers
frameworks/base/core/java/android/os/Looper.java has the source code
public class Looper { ... public void prepare() { ... } public static void loop() { ... } public void quit() { ... } ...
![Page 13: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/13.jpg)
Android Concurrency & Synchronization D. C. Schmidt
13
The Android Looper Class • A Looper provides a message
queue to a thread • By default Threads don’t have
a message loop associated with them
public class Thread implements Runnable { public static Thread currentThread() { ... } public final void join() { ... } public void interrupt() { ... } public synchronized void start() { ... } developer.android.com/reference/java/lang/Thread.html has more info
![Page 14: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/14.jpg)
Android Concurrency & Synchronization D. C. Schmidt
14
The Android Looper Class • A Looper provides a message
queue to a thread • By default Threads don’t have
a message loop associated with them • To create one, call
• prepare() in the thread that is to run the loop & then
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage (Message msg) { // process incoming msgs }}; Looper.loop(); }
developer.android.com/reference/android/os/Looper.html has more info
![Page 15: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/15.jpg)
Android Concurrency & Synchronization D. C. Schmidt
15
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage (Message msg) { // process incoming msgs }}; Looper.loop(); }
The Android Looper Class • A Looper provides a message
queue to a thread • By default Threads don’t have
a message loop associated with them • To create one, call
• prepare() in the thread that is to run the loop & then
• Create Handlers to process incoming messages (need not go here)
developer.android.com/reference/android/os/Looper.html has more info
![Page 16: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/16.jpg)
Android Concurrency & Synchronization D. C. Schmidt
16
The Android Looper Class • A Looper provides a message
queue to a thread • By default Threads don’t have
a message loop associated with them • To create one, call
• prepare() in the thread that is to run the loop & then
• Create Handlers to process incoming messages (need not go here)
• loop() to have it process messages until the loop is stopped
class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage (Message msg) { // process incoming msgs }}; Looper.loop(); }
developer.android.com/reference/android/os/Looper.html has more info
![Page 17: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/17.jpg)
Android Concurrency & Synchronization D. C. Schmidt
17
The Android Looper Class • A Looper provides a message
queue to a thread • By default Threads don’t have
a message loop associated with them
• HandlerThread is a helper class for starting a new Thread that automatically contains a Looper
class HandlerThread extends Thread { Looper mLooper; ... public void run() { Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); ... } ... onLooperPrepared(); Looper.loop(); ... protected void onLooperPrepared() { } }
Note the use of the Template Method
pattern to handle fixed steps in the algorithm
![Page 18: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/18.jpg)
Android Concurrency & Synchronization D. C. Schmidt
18 developer.android.com/reference/android/os/HandlerThread.html has more info
The Android Looper Class • A Looper provides a message
queue to a thread • By default Threads don’t have
a message loop associated with them
• HandlerThread is a helper class for starting a new Thread that automatically contains a Looper
class HandlerThread extends Thread { Looper mLooper; ... public void run() { Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); ... } ... onLooperPrepared(); Looper.loop(); ... protected void onLooperPrepared() { } }
This hook method enables subclasses to create Handlers
![Page 19: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/19.jpg)
Android Concurrency & Synchronization D. C. Schmidt
19 frameworks/base/core/java/android/os/HandlerThread.java has the source code
The Android Looper Class • A Looper provides a message
queue to a thread • By default Threads don’t have
a message loop associated with them
• HandlerThread is a helper class for starting a new Thread that automatically contains a Looper • The start() method must still
be called by client code to launch the thread
class HandlerThread extends Thread { Looper mLooper; ... public void run() { Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); ... } ... onLooperPrepared(); Looper.loop(); ... protected void onLooperPrepared() { } }
![Page 20: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/20.jpg)
Android Concurrency & Synchronization D. C. Schmidt
20
The Android Handler Class • Most interaction with a message
loop is through Handlers • A Handler allows sending &
processing of Message & Runnable objects associated with a Thread's MessageQueue
Loop
er Message
Message
Message
Message
Message
Message Queue
Thread1
Message
Runnable
Message
Handler
Handler
These Handlers are associated
with this Thread
![Page 21: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/21.jpg)
Android Concurrency & Synchronization D. C. Schmidt
21
• Most interaction with a message loop is through Handlers • A Handler allows sending &
processing of Message & Runnable objects associated with a Thread's MessageQueue
• Other Threads can communicate by exchanging Messages & Runnables via a Thread’s Handler(s)
Loop
er Message
Message
Message
Message
Message
Message Queue
Message
Runnable
Message
Handler
Handler
Thread2
Thread3
The Android Handler Class
developer.android.com/reference/android/os/Handler.html has more info
Thread1
![Page 22: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/22.jpg)
Android Concurrency & Synchronization D. C. Schmidt
22
The Android Handler Class • Most interaction with a message
loop is through Handlers • Each Handler object is associated
with a single Thread & that Thread's MessageQueue
public class Handler { ... public void handleMessage (Message msg) { }
Subclasses must override this hook method to process messages
![Page 23: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/23.jpg)
Android Concurrency & Synchronization D. C. Schmidt
23
The Android Handler Class • Most interaction with a message
loop is through Handlers • Each Handler object is associated
with a single Thread & that Thread's MessageQueue • When you create a new Handler,
it is bound to the Looper Thread (& its MessageQueue) of the Thread where it is created
public class Handler { ... public void handleMessage (Message msg) { } public Handler() { mLooper = Looper.myLooper(); if (mLooper == null) throw new RuntimeException( "Can't create handler inside thread that hasn’t called Looper.prepare()"); mQueue = mLooper.mQueue; ...
Handler constructor ensures that the object is used within
an initialized Looper
![Page 24: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/24.jpg)
Android Concurrency & Synchronization D. C. Schmidt
24
The Android Handler Class • Most interaction with a message
loop is through Handlers • Each Handler object is associated
with a single Thread & that Thread's MessageQueue • When you create a new Handler,
it is bound to the Looper Thread (& its MessageQueue) of the Thread where it is created
• From that point on, it will deliver Messages and Runnables to that Looper Thread’s MessageQueue & execute them as they come out of the queue
public class Looper { ... final MessageQueue mQueue; public static void loop() { ... for (;;) { Message msg = queue.next(); ... msg.target. dispatchMessage(msg); ... } ...
![Page 25: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/25.jpg)
Android Concurrency & Synchronization D. C. Schmidt
25
The Android Handler Class • Most interaction with a message
loop is through Handlers • Each Handler object is associated
with a single Thread & that Thread's MessageQueue
• Capabilities of a Handler • Sends Messages & posts
Runnables to a Thread • Thread’s MessageQueue
enqueues/schedules them for future execution
Runnable
Message
Handler
Handler
Thread2
Thread3
1. Handler.sendMessage(msg)
Thread1
2. Handler.post (new Runnable(){ public void run() { /* … */ }});)
![Page 26: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/26.jpg)
Android Concurrency & Synchronization D. C. Schmidt
26
The Android Handler Class • Most interaction with a message
loop is through Handlers • Each Handler object is associated
with a single Thread & that Thread's MessageQueue
• Capabilities of a Handler • Sends Messages & posts
Runnables to a Thread • Implements thread-safe
processing for Messages • In current Thread or
different Thread
Runnable
Message
Handler
Handler
Thread2
1. Handler.sendMessage(msg)
Thread1
frameworks/base/core/java/android/os/Handler.java has source code
3. handleMessage()
Thread3
2. Handler.post (new Runnable(){ public void run() { /* … */ }});)
![Page 27: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/27.jpg)
Android Concurrency & Synchronization D. C. Schmidt
27
boolean post(Runnable r)
• Add Runnable to MessageQueue
boolean postAtTime(Runnable r, long uptimeMillis)
• Add Runnable to MessageQueue • Run at a specific time (based on
SystemClock.upTimeMillis())
boolean postDelayed(Runnable r, long delayMillis)
• Add Runnable to the message queue • Run after specified amount of time
elapses
The Android Handler Class • Most interaction with a message
loop is through Handlers • Each Handler object is associated
with a single Thread & that Thread's MessageQueue
• Capabilities of a Handler • Sends Messages & posts
Runnables to a Thread • Implements thread-safe
processing for Messages • Handler methods associated
with Runnables
developer.android.com/reference/android/os/Handler.html has more info
![Page 28: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/28.jpg)
Android Concurrency & Synchronization D. C. Schmidt
28
boolean sendMessage(Message msg)
• Puts msg at end of queue immediately
boolean sendMessageAtFrontOfQueue (Message msg)
• Puts msg at front of queue immediately
boolean sendMessageAtTime (Message msg, long uptimeMillis)
• Puts msg on queue at stated time
boolean sendMessageDelayed (Message msg, long delayMillis)
• Puts msg after delay time has passed
The Android Handler Class • Most interaction with a message
loop is through Handlers • Each Handler object is associated
with a single Thread & that Thread's MessageQueue
• Capabilities of a Handler • Sends Messages & posts
Runnables to a Thread • Implements thread-safe
processing for Messages • Handler methods associated
with Runnables • Handler methods associated
with Messages
developer.android.com/reference/android/os/Handler.html has more info
![Page 29: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/29.jpg)
Android Concurrency & Synchronization D. C. Schmidt
29
• Android apps have a UI Thread • The UI Thread is a Looper
Summary
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
![Page 30: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/30.jpg)
Android Concurrency & Synchronization D. C. Schmidt
30
• Android apps have a UI Thread • App components in the same
process use the same UI Thread • User interaction, system
callbacks, & lifecycle methods are handled in the UI Thread
Summary
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
![Page 31: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/31.jpg)
Android Concurrency & Synchronization D. C. Schmidt
31
• Android apps have a UI Thread • App components in the same
process use the same UI Thread • Don’t access widgets in the UI
toolkit from non-UI Thread or block the UI Thread • Long-running operations should
execute in background Thread(s)
Summary
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
![Page 32: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/32.jpg)
Android Concurrency & Synchronization D. C. Schmidt
32
• Android apps have a UI Thread • App components in the same
process use the same UI Thread • Don’t access widgets in the UI
toolkit from non-UI Thread or block the UI Thread
• UI & background threads will need to communicate via • Sending Messages or posting
Runnables to the Looper Thread’s MessageQueue
Summary
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B
![Page 33: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/33.jpg)
Android Concurrency & Synchronization D. C. Schmidt
33
• Android apps have a UI Thread • App components in the same
process use the same UI Thread • Don’t access widgets in the UI
toolkit from non-UI Thread or block the UI Thread
• UI & background threads will need to communicate via • Sending Messages or posting
Runnables to the Looper Thread’s MessageQueue
• Executing operations in the background using AsyncTask
Summary
Async Task
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B
![Page 34: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/34.jpg)
Android Concurrency & Synchronization: Part 7
Douglas C. Schmidt
[email protected] www.dre.vanderbilt.edu/~schmidt
Institute for Software Integrated Systems
Vanderbilt University Nashville, Tennessee, USA
CS 282 Principles of Operating Systems II Systems Programming for Android
![Page 35: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/35.jpg)
Android Concurrency & Synchronization D. C. Schmidt
35
Async Task
Learning Objectives in this Part of the Module • Understand how to program with
the Android concurrency idioms • Handlers & Runnables • Handlers & Messages • AsyncTask
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B
![Page 36: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/36.jpg)
Android Concurrency & Synchronization D. C. Schmidt
36
• Create a Runnable, override its run() hook method, & pass to a Handler
Programming with the Handler & Runnables
Runnable
Handler
1. Handler.post (new Runnable(){ public void run() { /* … */ }});)
Background Thread
UI Thread (main thread)
![Page 37: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/37.jpg)
Android Concurrency & Synchronization D. C. Schmidt
37
• Create a Runnable, override its run() hook method, & pass to a Handler
• Looper framework calls run() method in the UI Thread
Programming with the Handler & Runnables
Runnable
Handler
1. Handler.post (new Runnable(){ public void run() { /* … */ }});)
Background Thread
2. handleMessage()
UI Thread (main thread)
3. run()
![Page 38: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/38.jpg)
Android Concurrency & Synchronization D. C. Schmidt
38
public class SimpleThreadingExample extends Activity { private ImageView iview; private Handler h = new Handler(); public void onCreate(Bundle savedInstanceState) { ... iview = ... final Button = ... button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new LoadIcon(R.drawable.icon)).start();
} }); } ...
Example of Runnables & Handlers
Create/start a new thread when user clicks a button
Pass the resource ID of the icon
Create new Handler in UI Thread
This code runs in the UI Thread
![Page 39: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/39.jpg)
Android Concurrency & Synchronization D. C. Schmidt
39
private class LoadIcon implements Runnable { int resId; LoadIconTask(int resId) { this.resId = resId; } public void run() final Bitmap tmp = BitmapFactory.decodeResource(getResources(), resId);
h.post(new Runnable() { public void run() { iview.setImageBitmap(tmp); } }); } ...
Example of Runnables & Handlers
Cache resource ID
Convert resource ID to bitmap
Create a new Runnable & post it to the UI Thread via the Handler
This code runs in a background thread
![Page 40: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/40.jpg)
Android Concurrency & Synchronization D. C. Schmidt
40
Posting Runnables on UI thread public class SimpleThreadingExample extends Activity { private Bitmap bitmap; public void onCreate(Bundle savedInstanceState) {
... final ImageView iview = ...; final Button b = ...; b.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap = ... iview.post(new Runnable() { public void run() { iview.setImageBitmap(bitmap);}
}); } }).start(); ...
developer.android.com/reference/android/view/View.html#post(java.lang.Runnable)
Create a new Runnable & post it to the UI Thread via the ImageView
![Page 41: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/41.jpg)
Android Concurrency & Synchronization D. C. Schmidt
41
Posting Runnables on UI thread public class SimpleThreadingExample extends Activity { private Bitmap bitmap; public void onCreate(Bundle savedInstanceState) {
... final ImageView iview = ...; final Button b = ...; b.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap = ...
SimpleThreadingExample.this .runOnUiThread(new Runnable() { public void run() { iview.setImageBitmap(bitmap);}
});} }).start();
developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Create a new Runnable & post it to the UI Thread via the Activity
![Page 42: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/42.jpg)
Android Concurrency & Synchronization D. C. Schmidt
42
• Extend the Handler class & override handleMessage() hook method
Programming with the Handler & Messages
UI Thread (main thread)
Message
Background Thread
Handler
1. Handler h = new Handler() { public void handleMessage (Message msg) { ... }
developer.android.com/reference/android/os/Handler.html#handleMessage(android.os.Message)
![Page 43: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/43.jpg)
Android Concurrency & Synchronization D. C. Schmidt
43
• Extend the Handler class & override handleMessage() hook method
• Create Message & set Message content • Handler.obtainMessage() • Message.obtain() • etc.
Programming with the Handler & Messages
UI Thread (main thread)
Message
Background Thread
Handler
2. Message msg = Handler.obtainMessage (SET_PROGRESS_BAR_VISIBILITY, ProgressBar.VISIBLE);
Message parameters include • int arg1, arg2 • int what • Object obj • Bundle data
developer.android.com/reference/android/os/Handler.html#obtainMessage(int, int)
![Page 44: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/44.jpg)
Android Concurrency & Synchronization D. C. Schmidt
44
• Extend the Handler class & override handleMessage() hook method
• Create Message & set Message content
• Looper framework calls the handleMessage() method in the UI Thread
Programming with the Handler & Messages
UI Thread (main thread)
Message
Background Thread
Handler
2. Message msg = Handler.obtainMessage (SET_PROGRESS_BAR_VISIBILITY, ProgressBar.VISIBLE);
3. void handleMessage(Message msg) { switch (msg.what) { case SET_PROGRESS_BAR_VISIBILITY: { progress.setVisibility((Integer) msg.obj); break; } ...
![Page 45: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/45.jpg)
Android Concurrency & Synchronization D. C. Schmidt
45
public class SimpleThreadingExample extends Activity { ... Handler h = new Handler() {
public void handleMessage(Message msg) { switch (msg.what) { case SET_PROGRESS_BAR_VISIBILITY: { progress.setVisibility((Integer) msg.obj); break; }
case PROGRESS_UPDATE: { progress.setProgress((Integer) msg.obj); break; }
case SET_BITMAP: { iview.setImageBitmap((Bitmap) msg.obj); break; }
} ...
Example of Messages & Handlers
Called back by Looper framework in UI Thread
![Page 46: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/46.jpg)
Android Concurrency & Synchronization D. C. Schmidt
46
public void onCreate(Bundle savedInstanceState) { ... iview = … progress = … final Button button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new Thread(new LoadIcon(R.drawable.icon, h)).start();
} }); } ...
Example of Messages & Handlers
Create/start a new thread when user clicks a button
Pass the resource ID of the icon
![Page 47: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/47.jpg)
Android Concurrency & Synchronization D. C. Schmidt
47
private class LoadIcon implements Runnable { public void run() { Message msg = h.obtainMessage (SET_PROGRESS_BAR_VISIBILITY, ProgressBar.VISIBLE);
h.sendMessage(msg); final Bitmap tmp = BitmapFactory.decodeResource(getResources(), resId); for (int i = 1; i < 11; i++) { msg = h.obtainMessage(PROGRESS_UPDATE, i * 10);
h.sendMessageDelayed(msg, i * 100); } msg = h.obtainMessage(SET_BITMAP, tmp); h.sendMessageAtTime(msg, 11 * 200); msg = h.obtainMessage(SET_PROGRESS_BAR_VISIBILITY, ProgressBar.INVISIBLE);
h.sendMessageAtTime(msg, 11 * 200); ...
Example of Messages & Handlers
Send various Messages
![Page 48: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/48.jpg)
Android Concurrency & Synchronization D. C. Schmidt
48
Programming with AsyncTask • AsyncTask provides a structured
way to manage work involving background & UI threads • Simplifies creation of long-
running tasks that need to communicate with the UI
developer.android.com/reference/android/os/AsyncTask.html has AsyncTask info
UI Thread (main thread)
Async Task
![Page 49: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/49.jpg)
Android Concurrency & Synchronization D. C. Schmidt
49
Programming with AsyncTask • AsyncTask provides a structured
way to manage work involving background & UI threads • Simplifies creation of long-
running tasks that need to communicate with the UI
• AsyncTask is designed as a helper class around Thread & Handler
frameworks/base/core/java/android/os/AsyncTask.java has the source code
UI Thread (main thread)
Async Task
![Page 50: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/50.jpg)
Android Concurrency & Synchronization D. C. Schmidt
50
Programming with AsyncTask
UI Thread (main thread)
Async Task
• AsyncTask provides a structured way to manage work involving background & UI threads
• Must be subclassed & hook methods overridden
frameworks/base/core/java/android/os/AsyncTask.java has the source code
class LoadIcon extends AsyncTask<Integer,Integer,Bitmap> { protected Bitmap doInBackground (Integer... resId) { ... }
protected void onProgressUpdate (Integer... values) { ... } protected void onPostExecute (Bitmap result) { ... } ...
![Page 51: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/51.jpg)
Android Concurrency & Synchronization D. C. Schmidt
52
public class SimpleThreadingExample extends Activity { ImageView iview; ProgressBar progress; public void onCreate(Bundle savedInstanceState) { ... iview = … progress = … final Button button = … button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new LoadIcon().execute(R.drawable.icon); } }); } ...
Example of Android AsyncTask
Create/start a new AsyncTask when user clicks a button
Pass the resource ID of the icon
![Page 52: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/52.jpg)
Android Concurrency & Synchronization D. C. Schmidt
53
class LoadIcon extends AsyncTask<Integer, Integer, Bitmap> { protected void onPreExecute() { progress.setVisibility(ProgressBar.VISIBLE); } protected Bitmap doInBackground(Integer... resId) { Bitmap tmp = BitmapFactory.decodeResource(getResources(), resId[0]);
publishProgress(...); return tmp; } ...
Example of Android AsyncTask
Convert resource ID to bitmap
Simulate long-running operation
Runs before doInBackground() in UI Thread Runs in background thread
Customize AsyncTask
![Page 53: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/53.jpg)
Android Concurrency & Synchronization D. C. Schmidt
54
class LoadIcon extends AsyncTask<Integer, Integer, Bitmap> { ... protected void onProgressUpdate(Integer... values) { progress.setProgress(values[0]); } protected void onPostExecute(Bitmap result) { progress.setVisibility(ProgressBar.INVISIBLE);
iview.setImageBitmap(result); } ...
Example of Android AsyncTask
Invoked in response to publishProgress() in UI Thread
Runs after doInBackground() in UI Thread
![Page 54: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/54.jpg)
Android Concurrency & Synchronization D. C. Schmidt
55
• Posting Runnables is simple, but not particularly flexible
Summary
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Handler
Background Thread B
![Page 55: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/55.jpg)
Android Concurrency & Synchronization D. C. Schmidt
56
• Posting Runnables is simple, but not particularly flexible
• Sending Messages is more flexible, but is more complicated to program
Summary
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B
![Page 56: Android Concurrency & Synchronization: Part 6schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization: Part 6 . ... Learning Objectives in this Part of the Module](https://reader031.vdocuments.mx/reader031/viewer/2022022017/5b16e87c7f8b9a4e6b8b4f4e/html5/thumbnails/56.jpg)
Android Concurrency & Synchronization D. C. Schmidt
57
• Posting Runnables is simple, but not particularly flexible
• Sending Messages is more flexible, but is more complicated to program
• AsyncTask is powerful, but is more complicated internally & has more overhead due to potential for more thread synchronization & schedulting
Summary
Loop
er Message
Message
Message
Message
Message
Message Queue
UI Thread (main thread)
Message
Runnable
Message
Background Thread A
Handler
Handler
Background Thread B