63
Android Concurrency & Synchronization: Part 4 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

Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

  • Upload
    others

  • View
    41

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization Part 4

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

2

Learning Objectives in this Part of the Module bull Understand the Android mechanisms available to implement concurrent apps

that synchronize amp schedule their interactions

Producer

put() take() Consumer

Synchronized Queue

put() take()

Android Concurrency amp Synchronization D C Schmidt

3

Motivating Java Synchronization amp Scheduling

bull Consider a concurrent producerconsumer portion of a Java app

Concurrent threads can corrupt the queuersquos

internal state if it is not synchronized properly

Likewise threads will lsquobusy waitrsquo when the queue is

empty or full which wastes CPU cycles unnecessarily

Producer

put() take() Consumer

Synchronized Queue

put() take()

Android Concurrency amp Synchronization D C Schmidt

4

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

5

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Resizable-array implementation

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

6

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Enqueue amp dequeue strings intofrom the queue

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

7

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Spawn producer amp consumer threads

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 2: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

2

Learning Objectives in this Part of the Module bull Understand the Android mechanisms available to implement concurrent apps

that synchronize amp schedule their interactions

Producer

put() take() Consumer

Synchronized Queue

put() take()

Android Concurrency amp Synchronization D C Schmidt

3

Motivating Java Synchronization amp Scheduling

bull Consider a concurrent producerconsumer portion of a Java app

Concurrent threads can corrupt the queuersquos

internal state if it is not synchronized properly

Likewise threads will lsquobusy waitrsquo when the queue is

empty or full which wastes CPU cycles unnecessarily

Producer

put() take() Consumer

Synchronized Queue

put() take()

Android Concurrency amp Synchronization D C Schmidt

4

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

5

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Resizable-array implementation

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

6

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Enqueue amp dequeue strings intofrom the queue

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

7

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Spawn producer amp consumer threads

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 3: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

3

Motivating Java Synchronization amp Scheduling

bull Consider a concurrent producerconsumer portion of a Java app

Concurrent threads can corrupt the queuersquos

internal state if it is not synchronized properly

Likewise threads will lsquobusy waitrsquo when the queue is

empty or full which wastes CPU cycles unnecessarily

Producer

put() take() Consumer

Synchronized Queue

put() take()

Android Concurrency amp Synchronization D C Schmidt

4

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

5

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Resizable-array implementation

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

6

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Enqueue amp dequeue strings intofrom the queue

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

7

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Spawn producer amp consumer threads

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 4: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

4

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

5

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Resizable-array implementation

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

6

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Enqueue amp dequeue strings intofrom the queue

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

7

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Spawn producer amp consumer threads

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 5: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

5

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Resizable-array implementation

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

6

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Enqueue amp dequeue strings intofrom the queue

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

7

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Spawn producer amp consumer threads

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 6: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

6

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Enqueue amp dequeue strings intofrom the queue

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

7

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Spawn producer amp consumer threads

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 7: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

7

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Spawn producer amp consumer threads

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 8: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

8

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

What output will this code produce

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 9: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

9

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void put(String msg) q_add(msg) public String take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

bull Consider a concurrent producerconsumer portion of a Java app bull Herersquos some example code that demonstrates the problem

Must protect critical sections from being run by two threads concurrently

Motivating Java Synchronization amp Scheduling

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 10: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

10

bull Java provides the ldquosynchronizedrdquo keyword to specify sections of code in an object that cannot be accessed concurrently by two threads

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt()

public void synchronized put(String msg) q_add(msg) public String synchronized take() return q_remove(0) public static void main(String argv[]) new Thread(new Runnable() public void run() for(int i = 0 i lt 10 i++) put(IntegertoString(i)) )start() new Thread(new Runnable() public void run() while(true) Systemoutprintln(take()) )start()

Partial Solution Using Java Synchronization

Only one synchronized method can be active in any given object

There are still problems with this solutionhellip

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 11: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

11

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 12: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

12

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

Better Solution Using Java Monitor Objects

See docsoraclecomjavasetutorialessentialconcurrencysyncmethhtml

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 13: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

13

bull All objects in Java can be Monitor Objects bull Methods requiring mutual

exclusion must be explicitly marked with the synchronized keyword

bull Access to a synchronized method is serialized wother synchronized methods

Better Solution Using Java Monitor Objects

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 14: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

14

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 15: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

15

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks bull eg

bull Synchronized blocks enable more fine-grained serialization

Better Solution Using Java Monitor Objects

void put(String msg) synchronized (this) q_add(msg) notifyAll()

public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 16: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

16

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 17: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

17

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 18: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

18

bull All objects in Java can be Monitor Objects

bull Java also supports synchronized blocks

bull Java objects have wait() amp notify()notifyAll() methods that allow callers to wait for a condition to become true bull Calling wait() on an object

will suspend current thread until a notify() call is made on the same object

bull Calling notifyAll() will wake up all waiting threads

Better Solution Using Java Monitor Objects public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

stackoverflowcomquestions37026java-notify-vs-notifyall-all-over-again

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 19: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

19

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 20: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

20

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

See docsoraclecomjavasetutorialessentialconcurrencyguardmethhtml

bull Always invoke wait() inside a loop that tests for the condition being waited for

bull Dont assume the notification was for the particular condition being waited for or that the condition is still true

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 21: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

21

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 22: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

22

bull Inside a synchronized method you can request a thread ldquowaitrdquo for a condition eg bull The synchronized take()

method acquires the monitor lock checks the queue size amp waits if the queue is empty

bull The thread blocking on wait() doesnrsquot continue until another thread notifies it that the queue has data to process

bull When the thread is notified it wakes up obtains the monitor lock continues after the wait() call amp releases the lock when the method returns

Detailed Analysis of wait() amp notifyAll() public class SynchronizedQueue private ListltStringgt q_ = new ArrayListltStringgt() public synchronized void put(String msg) q_add(msg) notifyAll() public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 23: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

23

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 24: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

24

Summary

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

bull Each Java object may be used as a monitor object bull Methods requiring mutual exclusion must be explicitly marked with the

synchronized keyword

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 25: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

25 docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Summary bull Each Java object may be used as a monitor object

bull Methods requiring mutual exclusion must be explicitly marked with the synchronized keyword

bull Blocks of code may also be marked by synchronized void put(String msg) synchronized (this) q_add(msg) notifyAll()

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 26: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

26

Summary bull Each Java object may be used as a monitor object bull Each monitor object in Java is equipped with a single wait queue in addition

to its entrance queue bull All waiting is done on this single wait queue amp all notify() amp notifyAll()

operations apply to this queue

enwikipediaorgwikiMonitor_(synchronization)Implicit_condition_variable_monitors

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

ltltcontainsgtgt 1

Wait Queue

ltltcontainsgtgt

Entrance Queue

1

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 27: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

27

Summary bull Production Java apps may need more than the simply monitor mechanisms

developerandroidcomreferencejavautilconcurrentlockspackage-summaryhtml

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 28: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization Part 5

Douglas C Schmidt

dschmidtvanderbiltedu wwwdrevanderbiltedu~schmidt

Institute for Software Integrated Systems

Vanderbilt University Nashville Tennessee USA

CS 282 Principles of Operating Systems II Systems Programming for Android

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 29: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

29

Learning Objectives in this Part of the Module bull Understand the Monitor Object pattern amp how it can be used to synchronize

amp schedule concurrent Android programs

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 30: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

30

Monitor Object POSA2 Concurrency Intent bull Synchronizes concurrent method execution to ensure only one method at

a time runs within an object bull Allows an objectrsquos methods to cooperatively schedule their execution

sequences

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 31: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

31

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 32: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

32

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 33: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

33

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 34: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

34

Applicability bull When an objectrsquos interface methods should define its synchronization

boundaries bull When only one method at a time should be active within the same object bull When objects should be responsible for method synchronization

transparently without requiring explicit client intervention bull When an objectrsquos methods may block during their execution

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 35: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

35

Structure amp Participants

Monitor Object POSA2 Concurrency

SynchronizedQueue

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 36: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

36

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Lock

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 37: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

37

Structure amp Participants

Monitor Object POSA2 Concurrency

Java Monitor Condition

Note that Java monitor objects only have a single (implicit) monitor condition

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 38: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

38

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method invocation

amp serialization

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 39: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

39

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

suspension

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 40: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

40

Dynamics

Monitor Object POSA2 Concurrency

Monitor condition notification

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 41: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

41

Dynamics

Monitor Object POSA2 Concurrency

Synchronized method thread

resumption

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 42: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

42

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

Monitor Object POSA2 Concurrency

See developerandroidcomreferenceandroidosCancellationSignalhtml

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 43: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

43

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress bull Used for long-running operations

like ContentResolverquery()

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel() See developerandroidcomreferenceandroidcontentContentResolverhtml

query(androidnetUri javalangString[] javalangString javalangString[] javalangString androidosCancellationSignal)

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 44: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

44

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) synchronized (this) while (mCancelInProgress) try wait() catch (InterruptedException ex) mOnCancelListener = listener

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 45: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

45

Monitor Object example in Android bull The CancellationSignal class

provides the ability to cancel an operation thatrsquos in progress

bull Several method are used to implement Monitor Object bull setOnCancelListener() ndash Sets

the cancellation listener whose onCancel() hook will be called when an operation is cancelled

bull cancel() ndash Cancels operation amp signals cancellation listener

Monitor Object POSA2 Concurrency

public final class CancellationSignal public void cancel() synchronized (this) mCancelInProgress = true try listeneronCancel() finally synchronized (this) mCancelInProgress = false notifyAll()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 46: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization

46

Douglas C Schmidt

Consequences + Simplification of concurrency control

bull Presents a concise programming model for sharing an object among cooperating threads where object synchronization corresponds to method invocations

Monitor Object POSA2 Concurrency

Producer

put() take() Consumer

Synchronized Queue

synchronized put() synchronized take()

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 47: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization

47

Douglas C Schmidt

Consequences + Simplification of concurrency control + Simplification of scheduling method execution

bull Synchronized methods use their monitor conditions to determine the circumstances under which they should suspend or resume their execution amp those of collaborating monitor objects

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 48: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization

48

Douglas C Schmidt

Consequences minus Limited Scalability

bull A single monitor lock can limit scalability due to increased contention when multiple threads serialize on a monitor object

Monitor Object POSA2 Concurrency

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 49: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization

49

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics

bull These result from the coupling between a monitor objectrsquos functionality amp its synchronization mechanisms

Monitor Object POSA2 Concurrency

public synchronized String take() while (q_isEmpty()) wait() return q_remove(0)

public synchronized void put(String msg) q_add(msg) notifyAll()

wisneskynetanomalypdf has info on the ldquoinheritance anomaly problemrdquo

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 50: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization

50

Douglas C Schmidt

Consequences minus Limited Scalability minus Complicated extensibility semantics minus Nested monitor lockout

bull This problem can occur when monitor objects are nested

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtC++2javahtml

class Inner protected boolean cond_ = false public synchronized void awaitCondition() while (cond) try wait () catch (InterruptedException e) public synchronized void signalCondition(boolean c) cond_ = c notifyAll ()

class Outer protected Inner inner_ = new Inner() public synchronized void process() inner_awaitCondition () public synchronized void set(boolean c) inner_signalCondition(c)

Holds the monitor lock

Method wonrsquot execute

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 51: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

51

Implementation bull Define the monitor objectrsquos

interface methods bull eg ArrayBlockingQueue

is a bounded BlockingQueue backed by an array that queues elements in FIFO order

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take()

developerandroidcomreferencejavautilconcurrentArrayBlockingQueuehtml

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 52: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

52

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull See the Thread-Safe

Interface pattern for design rationale

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) public E take() private void insert(E x) private E extract()

wwwdrevanderbiltedu~schmidtPDFlocking-patternspdf has more info

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 53: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

53

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms bull Can use classes defined

in the javautilconcurrent package

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable final Object[] items int takeIndex int putIndex int count final ReentrantLock lock private final Condition notEmpty private final Condition notFull

See Lockhtml amp Conditionhtml at developerandroidcomreferencejavautilconcurrentlocks

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 54: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

54

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public void put(E e) throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == itemslength) notFullawait() insert(e) finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 55: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

55

Implementation bull Define the monitor objectrsquos

interface methods bull Define the monitor objectrsquos

implementation methods bull Define the monitor objectrsquos

internal state amp synchronization mechanisms

bull Implement all the monitor objectrsquos methods amp data members bull Note the Java synchronized

keyword isnrsquot used here

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

libcorelunisrcmainjavajavautilconcurrentArrayBlockingQueuejava

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 56: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

56

Known Uses bull Dijkstra amp Hoare-style Monitors

Monitor Object POSA2 Concurrency

enwikipediaorgwikiMonitor_(synchronization) describes monitors

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 57: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

57

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Note how few synchronized

methodsblocks are used in javautilconcurrency yet this pattern is still widely applied

Monitor Object POSA2 Concurrency public class ArrayBlockingQueueltEgt extends AbstractQueueltEgt implements BlockingQueueltEgt javaioSerializable public E take() throws InterruptedException final ReentrantLock lock = thislock locklockInterruptibly() try while (count == 0) notEmptyawait() return extract() finally lockunlock()

docsoraclecomjavasetutorialessentialconcurrencylocksynchtml has more

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 58: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

58

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal

Monitor Object POSA2 Concurrency

public final class CancellationSignal private boolean mCancelInProgress public void setOnCancelListener (OnCancelListener listener) public void cancel()

frameworksbasecorejavaandroidosCancellationSignaljava has the code

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 59: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

59

Known Uses bull Dijkstra amp Hoare-style Monitors bull Java objects with synchronized

methodsblocks bull Android CancellationSignal bull ACE provides portable C++

building blocks for implementing monitor objects

Monitor Object POSA2 Concurrency

wwwdrevanderbiltedu~schmidtPDFACE-concurrencypdf has more info

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 60: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

60

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 61: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

61

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 62: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

62

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads bull To protect the internal state of shared objects it is necessary to

synchronize amp schedule client access to them bull To simplify programming however clients should not need to distinguish

programmatically between accessing shared amp non-shared components

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary
Page 63: Android Concurrency & Synchronization: Part 4schmidt/cs282/PDFs/Concurrency-and... · Android Concurrency & Synchronization D. C. Schmidt . 17 • All objects in Java can be Monitor

Android Concurrency amp Synchronization D C Schmidt

63

Summary

bull Concurrent software often contains objects whose methods are invoked by multiple client threads

bull The Monitor Object pattern enables the sharing of object by client threads that self-coordinate a serializedmdashyet interleavedmdashexecution sequence

See wwwdrevanderbiltedu~schmidtPDFmonitorpdf for Monitor Object

  • Slide Number 1
  • Learning Objectives in this Part of the Module
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Motivating Java Synchronization amp Scheduling
  • Partial Solution Using Java Synchronization
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Better Solution Using Java Monitor Objects
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Detailed Analysis of wait() amp notifyAll()
  • Summary
  • Summary
  • Summary
  • Summary
  • Summary
  • Slide Number 28
  • Learning Objectives in this Part of the Module
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Monitor Object POSA2 Concurrency
  • Summary
  • Summary
  • Summary
  • Summary