android concurrency & synchronization: introduction - distributed

69
Android Concurrency & Synchronization: Introduction 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

Upload: others

Post on 11-Feb-2022

19 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency &

Synchronization: Introduction

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: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

2

• Explore the motivations for & challenges of concurrent software

Concurrent software can simultaneously run multiple computations that potentially interact with each other

Introduction

Page 3: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

3

• Explore the motivations for & challenges of concurrent software

• Understand the mechanisms that Android provides to manage multiple threads that run concurrently within a process

Introduction

Process A Process B Process C

Page 4: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

4

• Explore the motivations for & challenges of concurrent software

• Understand the mechanisms that Android provides to manage multiple threads that run concurrently within a process

• Some Android mechanisms are based on standard Java threading & locking mechanisms

Introduction

Page 5: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

5

• Explore the motivations for & challenges of concurrent software

• Understand the mechanisms that Android provides to manage multiple threads that run concurrently within a process

• Some Android mechanisms are based on standard Java threading & locking mechanisms

• Other mechanisms are based on Android concurrency idioms

Introduction

Lo

op

er Message

Message

Message

Message

Message

Message

Queue

UI Thread (main thread)

Message

Message

Background

Thread A

Handler

Message

Handler

Background

Thread B

Async

Task

Page 6: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency &

Synchronization: Part 1

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 7: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

7

Learning Objectives in this Part of the Module

• Understand the motivations for & challenges of concurrent software

Page 8: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

8

• Leverage hardware/software advances

• e.g., multi-core processors & multi-threaded operating systems, virtual machines, & middleware

Motivations for Concurrent Software

www.androidauthority.com/tag/quad-core-phones has more info

Page 9: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

9

Motivations for Concurrent Software • Leverage hardware/software

advances

• Simplify program structure

• e.g., by allow blocking operations

• Classic single architectures can’t perform blocking operations

• This complicates app implementations by decoupling the flow of control in time & space

Lo

op

er Message

Message

Message

Message

Message

Message

Queue

UI Thread (main thread)

Message

Page 10: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

10

Motivations for Concurrent Software • Leverage hardware/software

advances

• Simplify program structure

• e.g., by allow blocking operations

Modern multi-threaded architectures support blocking I/O in certain

contexts L

oo

pe

r Message

Message

Message

Message

Message

Message

Queue

UI Thread (main thread)

Message

Message

Background

Thread A

Handler

Message

Handler

Background

Thread B

Async

Task

Page 11: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

11

Motivations for Concurrent Software

private Bitmap bitmap;

final ImageView iview = ...

final Button button = ...

button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

new Thread(new Runnable() {

public void run() {

bitmap = downloadImage(URI);

iview.post(new Runnable() {

public void run() { iview.setImageBitmap(bitmap);}

});

}

}).start();

• Leverage hardware/software advances

• Simplify program structure

• e.g., by allow blocking operations

Multi-threaded Android example

developer.android.com/guide/components/processes-and-threads.html#WorkerThreads

Page 12: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

12

Motivations for Concurrent Software

private Bitmap bitmap;

final ImageView iview = ...

final Button button = ...

button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

new Thread(new Runnable() {

public void run() {

bitmap = downloadImage(URI);

iview.post(new Runnable() {

public void run() { iview.setImageBitmap(bitmap);}

});

}

}).start(); Start a new thread

Download an image

Display bitmap in the UI thread

Handles button clicks

• Leverage hardware/software advances

• Simplify program structure

• e.g., by allow blocking operations

developer.android.com/guide/components/processes-and-threads.html#WorkerThreads

Page 13: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

13

• Leverage hardware/software advances

• Simplify program structure

• Increase performance

• Parallelize computations & communications

Motivations for Concurrent Software

Page 14: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

14

• Leverage hardware/software advances

• Simplify program structure

• Increase performance

• Improve response-time

• e.g., don’t starve the UI thread

Motivations for Concurrent Software

Page 15: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

15

• Accidental Complexities

Challenges for Concurrent Software

Stem from limitations with development tools & techniques

Page 16: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

16

• Accidental Complexities

• Low-level APIs

• Tedious, error-prone, & non-portable

Challenges for Concurrent Software

See www.dre.vanderbilt.edu/~schmidt/PDF/BC-schmidt.pdf for more info

Page 17: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

17

• Accidental Complexities

• Low-level APIs

typedef struct

{ char message_[20]; int thread_id_; } PARAMS;

void *print_hello_world (void *ptr) {

PARAMS *params = (PARAMS *) ptr;

printf ("%s from thread %d\n",

params->message_, params->thread_id_);

}

int main (void) {

pthread_t thread; PARAMS params;

params.thread_id_ = 1; strcpy (params.message_, "Hello World");

pthread_create (&thread, 0, &print_hello_world,

(void *) &params);

/* ... */

pthread_join(thread, 0);

return 0;

}

Challenges for Concurrent Software

Pointer-to-function

Cast to void *

Cast from void *

“Quasi-typed” thread handle

Not portable to non-POSIX platforms

Page 18: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

18

• Accidental Complexities

• Low-level APIs

Challenges for Concurrent Software

Other C threading APIs have similar accidental complexities

typedef struct

{ char message_[20]; int thread_id_; } PARAMS;

void *print_hello_world (void *ptr) {

PARAMS *params = (PARAMS *) ptr;

printf ("%s from thread %d\n",

params->message_, params->thread_id_);

}

int main (void) {

pthread_t thread; PARAMS params;

params.thread_id_ = 1; strcpy (params.message_, "Hello World");

pthread_create (&thread, 0, &print_hello_world,

(void *) &params);

/* ... */

pthread_join(thread, 0);

return 0;

}

Page 19: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

19

• Accidental Complexities

• Low-level APIs

• Limited debugging tools

Challenges for Concurrent Software

Page 20: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

20

• Accidental Complexities

• Low-level APIs

• Limited debugging tools

Challenges for Concurrent Software

See www.dre.vanderbilt.edu/~schmidt/PDF/DSIS.pdf & www.fluid.cs.cmu.edu

Page 21: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

21

Challenges for Concurrent Software

Stem from fundamental domain

challenges

• Accidental Complexities

• Inherent Complexities

Page 22: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

22

• Accidental Complexities

• Inherent Complexities

• Synchronization

Challenges for Concurrent Software

en.wikipedia.org/wiki/Synchronization_(computer_science) has more info

Synchronization is the application of mechanisms to ensure that two concurrently-

executing threads do not execute specific portions of a program at the same time

Page 23: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

23

• Accidental Complexities

• Inherent Complexities

• Synchronization

• Scheduling

Challenges for Concurrent Software

en.wikipedia.org/wiki/Scheduling_(computing) has more info

Scheduling is the method by which threads, processes, or data flows are

given access to system resources

Page 24: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

24

• Accidental Complexities

• Low-level APIs

• Limited debugging tools

• Inherent Complexities

• Synchronization

• Scheduling

• Deadlocks

Challenges for Concurrent Software

L2

L1

T2 T1

<<owns>>

<<owns>> <<needs>>

<<needs>>

• Accidental Complexities

• Inherent Complexities

• Synchronization

• Scheduling

• Deadlock

See en.wikipedia.org/wiki/Deadlock for more info

A deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does

Page 25: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

25

Summary • Concurrent software helps

• Leverage advances in hardware technology

• Meet the quality & performance needs of apps & services

Page 26: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

26

Summary • Concurrent software helps

• Leverage advances in hardware technology

• Meet the quality & performance needs of apps & services

• Successful concurrent software solutions must address key accidental & inherent complexities arising from

• Limitations with development tools/techniques

Page 27: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

27

Summary • Concurrent software helps

• Leverage advances in hardware technology

• Meet the quality & performance needs of apps & services

• Successful concurrent software solutions must address key accidental & inherent complexities arising from

• Limitations with development tools/techniques

• Fundamental domain challenges

Page 28: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency &

Synchronization: Part 2

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 29: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

29

• Understand how to program Java mechanisms available in Android to implement concurrent apps that process requests simultaneously via multithreading

Learning Objectives in this Part of the Module

Process A Process B Process C

Page 30: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

30

Overview of Java Threads in Android

• Android implements many standard Java concurrency & synchronization classes

See docs.oracle.com/javase/tutorial/essential/concurrency

Page 31: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

31

Overview of Java Threads in Android

• Android implements many standard Java concurrency & synchronization classes

• Conceptual view

• Concurrent computations running in a (Linux) process that can communicate with each other via shared memory or message passing

Process A Process B Process C

Page 32: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

32

Overview of Java Threads in Android

• Android implements many standard Java concurrency & synchronization classes

• Conceptual view

• Implementation view

• Each Java thread has a program counter & a stack (unique)

• The heap & static areas are shared across threads (common)

See developer.android.com/guide/components/processes-and-threads.html

Process A Process B Process C

Page 33: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

33

public class MyThread

extends Thread {

public void run() {

//code to run goes here

}

}

MyThread myt = new MyThread();

myt.start();

• All threads must be given some code to run by either

• Extending the Thread class

Using Java Threads in Android

Thread

MyThread

Starting a thread using a named class (or inner class)

Page 34: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

34

• All threads must be given some code to run by either

• Extending the Thread class

• Implementing the Runnable interface

Using Java Threads in Android

Runnable public interface Runnable {

public void run();

}

public class MyRunnable

implements Runnable {

public void run() {

//code to run goes here

}

}

MyRunnable myr = new MyRunnable();

new Thread(myr).start();

MyRunnable

Starting a thread using a named implementation of

Runnable

Page 35: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

35

• All threads must be given some code to run by either

• Extending the Thread class

• Implementing the Runnable interface

Using Java Threads in Android

Runnable public interface Runnable {

public void run();

}

new Thread(new Runnable() {

public void run(){

//code to run goes here

}

}).start();

MyRunnable

Starting a thread using an anonymous class (or inner

class) as the Runnable

Page 36: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

36

• All threads must be given some code to run

• Android calls the Thread/Runnable run() method after a new thread starts up

: My

Component

onCreate()

start()

run()

new()

Using Java Threads in Android

Run concurrently

: MyThread

Page 37: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

37

• All threads must be given some code to run

• Android calls the Thread/Runnable run() method after a new thread starts up

• You can run any code in a thread, but it must be inside of a run() method or called from a run() method

: My

Component

onCreate()

start()

run()

new()

Using Java Threads in Android

Run concurrently

: MyThread

Page 38: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

38

• All threads must be given some code to run

• Android calls the Thread/Runnable run() method after a new thread starts up

• The thread can be active as long as the run() method hasn’t returned

• Naturally, the Android scheduler can suspend/resume threads

: My

Component

onCreate()

start()

run()

new()

Using Java Threads in Android

join()

: MyThread

Page 39: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

39

• All threads must be given some code to run

• Android calls the Thread/Runnable run() method after a new thread starts up

• The thread can be active as long as the run() method hasn’t returned

• Naturally, the Android scheduler can suspend/resume threads

• If you want thread to run “forever,” you need to have a while(true) statement in that run() method

: My

Component

onCreate()

start()

run()

new()

Using Java Threads in Android

join()

: MyThread

Page 40: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

40

: My

Component

onCreate()

Using Java Threads in Android

• All threads must be given some code to run

• Android calls the Thread/Runnable run() method after a new thread starts up

• The thread can be active as long as the run() method hasn’t returned

• When run() returns the thread is no longer active

Page 41: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

41

Summary

• Some concurrency mechanisms provided by Android are based on standard Java threading classes

Page 42: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency &

Synchronization: Part 3

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 43: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

43

Learning Objectives in this Part of the Module

• Understand how the Java concurrency mechanisms available in Android are implemented

Page 44: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

44

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 45: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

45

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 46: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

46

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 47: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

47

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 48: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

48

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 49: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

49

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 50: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

50

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 51: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

51

Scheduler

Sleeping

new MyThread()

myThread.start()

Created

Blocking resource obtained attempt to access

guarded resource

Runnable

Waiting

lock.notify(), lock.notifyAll()

lock.wait()

myThread.sleep()

sleeptime elapsed

Running

run() method returns

Terminated

State Machine for Java Threads in Android

Page 52: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

52

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

1. MyThread.start()

Page 54: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

54

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

1. MyThread.start()

2. Thread.start() // Java method

3. VMThread.create() // Native method

See libcore/luni/src/main/java/java/lang/VMThread.java

Page 55: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

55

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

1. MyThread.start()

2. Thread.start() // Java method

3. VMThread.create() // Native method

4. Dalvik_java_lang_VMThread_create(const u4* args,

JValue* pResult) // JNI method

See dalvik/vm/native/java_lang_VMThread.cpp

Page 56: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

56

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

1. MyThread.start()

2. Thread.start() // Java method

3. VMThread.create() // Native method

4. Dalvik_java_lang_VMThread_create(const u4* args,

JValue* pResult) // JNI method

5. dvmCreateInterpThread(Object* threadObj,

int reqStackSize) // Dalvik method

See dalvik/vm/Thread.cpp

Page 57: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

57

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

Runtime thread stack

1. MyThread.start()

2. Thread.start() // Java method

3. VMThread.create() // Native method

4. Dalvik_java_lang_VMThread_create(const u4* args,

JValue* pResult) // JNI method

5. dvmCreateInterpThread(Object* threadObj,

int reqStackSize) // Dalvik method

6. pthread_create(&threadHandle, &threadAttr,

interpThreadStart, newThread) // Pthreads method

See bionic/libc/bionic/pthread.c

Page 58: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

58

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

Runtime thread stack

1. MyThread.start()

2. Thread.start() // Java method

3. VMThread.create() // Native method

4. Dalvik_java_lang_VMThread_create(const u4* args,

JValue* pResult) // JNI method

5. dvmCreateInterpThread(Object* threadObj,

int reqStackSize) // Dalvik method

6. pthread_create(&threadHandle, &threadAttr,

interpThreadStart, newThread) // Pthreads method

7. interpThreadStart(void* arg) // Adapter

See dalvik/vm/Thread.cpp

Page 59: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

59

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

Runtime thread stack

1. MyThread.start()

2. Thread.start() // Java method

3. VMThread.create() // Native method

4. Dalvik_java_lang_VMThread_create(const u4* args,

JValue* pResult) // JNI method

5. dvmCreateInterpThread(Object* threadObj,

int reqStackSize) // Dalvik method

6. pthread_create(&threadHandle, &threadAttr,

interpThreadStart, newThread) // Pthreads method

7. interpThreadStart(void* arg) // Adapter

8. dvmCallMethod(self, run,

self->threadObj,

&unused) // Dalvik method

See dalvik/vm/interp/Stack.cpp

Page 60: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

60

Starting Java Threads • When start() is called on a Java Thread object a whole series of steps occur

Runtime thread stack

1. MyThread.start()

2. Thread.start() // Java method

3. VMThread.create() // Native method

4. Dalvik_java_lang_VMThread_create(const u4* args,

JValue* pResult) // JNI method

5. dvmCreateInterpThread(Object* threadObj,

int reqStackSize) // Dalvik method

6. pthread_create(&threadHandle, &threadAttr,

interpThreadStart, newThread) // Pthreads method

7. interpThreadStart(void* arg) // Adapter

8. dvmCallMethod(self, run,

self->threadObj,

&unused) // Dalvik method

9. MyThread.run() // User-defined hook

Page 61: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

61

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• If you are going to create a long running operation inside of your run() method, you must ensure your code can stop voluntarily!

Process

Page 62: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

62

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• One way to stop a thread is to use the interrupt() method

• This method sends an interrupt request to the designated thread

Thread t1 =

new Thread(new Runnable() {

public void run(){

for (int i = 0;

i < input.length;

i++) {

process(input[i]);

if (Thread.interrupted())

throw InterruptedException();

}

}

t1.start();

...

t1.interrupt();

Page 63: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

63

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• One way to stop a thread is to use the interrupt() method

• This method sends an interrupt request to the designated thread

• Check Thread.interrupted() periodically to see if the thread’s been stopped & throw InterruptedException

Thread t1 =

new Thread(new Runnable() {

public void run(){

for (int i = 0;

i < input.length;

i++) {

process(input[i]);

if (Thread.interrupted())

throw InterruptedException();

}

}

t1.start();

...

t1.interrupt();

Page 64: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

64

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• One way to stop a thread is to use the interrupt() method

• This method sends an interrupt request to the designated thread

• Check Thread.interrupted() periodically to see if the thread’s been stopped & throw InterruptedException

• Certain blocking operations will be automatically be interrupted

• e.g., wait(), join(), sleep() & blocking I/O calls

Thread t1 =

new Thread(new Runnable() {

public void run(){

for (int i = 0;

i < input.length;

i++) {

process(input[i]);

if (Thread.interrupted())

throw InterruptedException();

}

}

t1.start();

...

t1.interrupt();

See developer.android.com/reference/java/lang/Thread.html#interrupt()

Page 65: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

65

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• One way to stop a thread is to use the interrupt() method

• Another way is to use a “stop” flag

public class MyRunnable

implements Runnable {

private volatile boolean

running_ = true;

public void stop() {

running_ = false;

}

public void run() {

while(running_) {

// do stuff

}

}

}

Page 66: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

66

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• One way to stop a thread is to use the interrupt() method

• Another way is to use a “stop” flag

• Add a volatile boolean flag “running_” to your class that implements Runnable

• Initially, set “running_” to true

public class MyRunnable

implements Runnable {

private volatile boolean

running_ = true;

public void stop() {

running_ = false;

}

public void run() {

while(running_) {

// do stuff

}

}

}

en.wikipedia.org/wiki/Volatile_variable#In_Java has more on volatile

Page 67: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

67

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• One way to stop a thread is to use the interrupt() method

• Another way is to use a “stop” flag

• Add a volatile boolean flag “running_” to your class that implements Runnable

• Have a stop() method that sets “running_” to false

public class MyRunnable

implements Runnable {

private volatile boolean

running_ = true;

public void stop() {

running_ = false;

}

public void run() {

while(running_) {

// do stuff

}

}

}

Page 68: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

68

Stopping Java Threads • Other than returning from run(), there’s no “stop” method for a Java Thread

• One way to stop a thread is to use the interrupt() method

• Another way is to use a “stop” flag

• Add a volatile boolean flag “running_” to your class that implements Runnable

• Have a stop() method that sets “running_” to false

• Check “running_” periodically to see if the thread’s been stopped

public class MyRunnable

implements Runnable {

private volatile boolean

running_ = true;

public void stop() {

running_ = false;

}

public void run() {

while(running_) {

// do stuff

}

}

}

This solution requires developers to periodically check if thread was stopped

Page 69: Android Concurrency & Synchronization: Introduction - Distributed

Android Concurrency & Synchronization D. C. Schmidt

69

Summary

• Java Threads are implemented using various methods & functions defined by lower layers of the Android software stack