Monitors & Condition Synchronization

Similar documents
Lecture 6: Introduction to Monitors and Semaphores

Chapter 8 Implementing FSP Models in Java

3C03 Concurrency: Condition Synchronisation

Outline of this lecture G52CON: Concepts of Concurrency

Lecture 8: Safety and Liveness Properties

Concurrent programming in Java

Last Class: Semaphores

Monitors, Java, Threads and Processes

Parallel Programming

! Past few lectures: Ø Locks: provide mutual exclusion Ø Condition variables: provide conditional synchronization

Concurrent Programming

Semaphores and Monitors: High-level Synchronization Constructs

4. Monitors. Monitors support data encapsulation and information hiding and are easily adapted to an object-oriented environment.

CS11 Java. Fall Lecture 7

Lecture 6: Semaphores and Monitors

Monitors and Semaphores

Chapter 6 Concurrent Programming

Mutual Exclusion using Monitors

Monitor Object. An Object Behavioral Pattern for Concurrent Programming. Douglas C. Schmidt

Deadlock Victim. dimanche 6 mai 12

Resurrecting Ada s Rendez-Vous in Java

MonitorExplorer: A State Exploration-Based Approach to Testing Java Monitors

Hoare-Style Monitors for Java

Built-in Concurrency Primitives in Java Programming Language. by Yourii Martiak and Mahir Atmis

Overview. CMSC 330: Organization of Programming Languages. Synchronization Example (Java 1.5) Lock Interface (Java 1.5) ReentrantLock Class (Java 1.

Thread Synchronization and the Java Monitor

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)

Computing Concepts with Java Essentials

Threads 1. When writing games you need to do more than one thing at once.

Java Virtual Machine Locks

TESTING JAVA MONITORS BY STATE SPACE EXPLORATION MONICA HERNANDEZ. Presented to the Faculty of the Graduate School of

OBJECT ORIENTED PROGRAMMING LANGUAGE

Distributed Systems [Fall 2012]

Traditional Software Development. Model Requirements and JAVA Programs. Formal Verification & Validation. What is a state?

Shared Address Space Computing: Programming

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

COS 318: Operating Systems. Semaphores, Monitors and Condition Variables

Real Time Programming: Concepts

Java the UML Way: Integrating Object-Oriented Design and Programming

Pemrograman Dasar. Basic Elements Of Java

SYSTEM ecos Embedded Configurable Operating System

Java Concurrency Framework. Sidartha Gracias

Priority Based Implementation in Pintos

Java Memory Model: Content

Concepts of Concurrent Computation

Fundamentals of Java Programming

Object Oriented Software Design

Threads & Tasks: Executor Framework

Java SE 8 Programming

6 Synchronization with Semaphores

Object Oriented Software Design

OPERATING SYSTEMS PROCESS SYNCHRONIZATION

JAVA - MULTITHREADING

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Priority Inversion Problem and Deadlock Situations

Formal Verification by Model Checking

Design Patterns in C++

KWIC Implemented with Pipe Filter Architectural Style

Computer Programming I

Paper 3F6: Software Engineering and Systems Distributed Systems Design Solutions to Examples Paper 3

Building a Multi-Threaded Web Server

Advanced Multiprocessor Programming

An Overview of Java. overview-1

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Overview Motivating Examples Interleaving Model Semantics of Correctness Testing, Debugging, and Verification

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Conditionals (with solutions)

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

How To Write A Multi Threaded Software On A Single Core (Or Multi Threaded) System

J a v a Quiz (Unit 3, Test 0 Practice)

CS Fall 2008 Homework 2 Solution Due September 23, 11:59PM

Creating a Simple, Multithreaded Chat System with Java

Topics. Producing Production Quality Software. Concurrent Environments. Why Use Concurrency? Models of concurrency Concurrency in Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Programma della seconda parte del corso

The ConTract Model. Helmut Wächter, Andreas Reuter. November 9, 1999

Android Application Development Course Program

Java (12 Weeks) Introduction to Java Programming Language

Crash Course in Java

Dynamic Thread Pool based Service Tracking Manager

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Chapter 1 FUNDAMENTALS OF OPERATING SYSTEM

Chapter 2: Elements of Java

Modeling Kahn Process Networks in the Dynamic Dataflow Formalism

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Communications Software Engineering Design Model

Kirsten Sinclair SyntheSys Systems Engineers

Testing and Inspecting to Ensure High Quality

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

OVERVIEW OF THE PROJECT...

Transcription:

Chapter 5 Monitors & Condition Synchronization 1

monitors & condition synchronization Concepts: monitors: encapsulated data + access procedures mutual exclusion + condition synchronization nested monitors Models: guarded actions Practice: private data and synchronized methods (exclusion). wait(), notify() and notifyall() for condition synch. single thread active in the monitor at a time 2

5.1 Condition synchronization A controller is required for a carpark, which only permits cars to enter when the carpark is not full and permits cars to leave when there it is not empty. Car arrival and departure are simulated by separate threads. 3

carpark model Events or actions of interest? arrive and depart Identify processes. arrivals, departures and carpark control Define each process and interactions (structure). CARPARK ARRIVALS arrive CARPARK CONTROL depart DEPARTURES 4

carpark model CARPARKCONTROL(N=4) = SPACES[N], SPACES[i:0..N] = (when(i>0) arrive->spaces[i-1] when(i<n) depart->spaces[i+1] ). ARRIVALS = (arrive->arrivals). DEPARTURES = (depart->departures). CARPARK = (ARRIVALS CARPARKCONTROL(4) DEPARTURES). Guarded actions are used to control arrive and depart. LTS? 5

carpark program Model - all entities are processes interacting by actions Program - need to identify threads and monitors thread - active entity which initiates (output) actions monitor - passive entity which responds to (input) actions. For the carpark? CARPARK ARRIVALS arrive CARPARK CONTROL depart DEPARTURES 6

carpark program - class diagram Applet Runnable CarPark arrivals, departures ThreadPanel Arrivals carpark cardisplay Departures CarParkCanvas disp CarParkControl arrive() depart() DisplayCarPark We have omitted DisplayThread and GraphicCanvas threads managed by ThreadPanel. 7

carpark program Arrivals and Departures implement Runnable, CarParkControl provides the control (condition synchronization). Instances of these are created by the start() method of the CarPark applet : public void start() { CarParkControl c = new DisplayCarPark(carDisplay,Places); arrivals.start(new Arrivals(c)); departures.start(new Departures(c)); 8

carpark program - Arrivals and Departures threads class Arrivals implements Runnable { CarParkControl carpark; Arrivals(CarParkControl c) {carpark = c; public void run() { try { while(true) { ThreadPanel.rotate(330); carpark.arrive(); ThreadPanel.rotate(30); catch (InterruptedException e){ Similarly Departures which calls carpark.depart(). How do we implement the control of CarParkControl? 9

Carpark program - CarParkControl monitor class CarParkControl { protected int spaces; protected int capacity; CarParkControl(int n) {capacity = spaces = n; synchronized void arrive() { --spaces; synchronized void depart() { ++spaces; mutual exclusion by synch methods condition synchronization? block if full? (spaces==0) block if empty? (spaces==n) 10

condition synchronization in Java Java provides a thread wait set per monitor (actually per object) with the following methods: public final void notify() Wakes up a single thread that is waiting on this object's wait set. public final void notifyall() Wakes up all threads that are waiting on this object's wait set. public final void wait() throws InterruptedException Waits to be notified by another thread. The waiting thread releases the synchronization lock associated with the monitor. When notified, the thread must wait to reacquire the monitor before resuming execution. 11

condition synchronization in Java We refer to a thread entering a monitor when it acquires the mutual exclusion lock associated with the monitor and exiting the monitor when it releases the lock. Wait() - causes the thread to exit the monitor, permitting other threads to enter the monitor. Thread A notify() Monitor data wait() Thread B 12

Thread F C Thread E F monitor lock Thread B E Monitor Thread B data wait() Thread A notify() Thread A C Thread A wait 13

condition synchronization in Java FSP: when cond act -> NEWSTAT Java: public synchronized void act() throws InterruptedException { while (!cond) wait(); // modify monitor data notifyall() The while loop is necessary to retest the condition cond to ensure that cond is indeed satisfied when it re-enters the monitor. notifyall() is necessary to awaken other thread(s) that may be waiting to enter the monitor now that the monitor data has been changed. 14

CarParkControl - condition synchronization class CarParkControl { protected int spaces; protected int capacity; CarParkControl(int n) {capacity = spaces = n; synchronized void arrive() throws InterruptedException { while (spaces==0) wait(); block if full --spaces; notifyall(); synchronized void depart() throws InterruptedException { while (spaces==capacity) wait(); block if empty ++spaces; notifyall(); Is it safe to use notify() rather than notifyall()? 15

models to monitors - summary Active entities (that initiate actions) are implemented as threads. Passive entities (that respond to actions) are implemented as monitors. Each guarded action in the model of a monitor is implemented as a synchronized method which uses a while loop and wait() to implement the guard. The while loop condition is the negation of the model guard condition. Changes in the state of the monitor are signaled to waiting threads using notify() or notifyall(). 16

5.2 Semaphores Semaphores are a low-level, primitive construct widely used for dealing with inter-process synchronization in operating systems. Semaphore s is an integer variable that can take only non-negative values. The only operations permitted on s are up(s) and down(s). Blocked processes are held in a FIFO queue. down(s): if s >0 then decrement s else block execution of the calling process up(s): if processes blocked on s then awaken one of them else increment s 17

modeling semaphores To ensure analyzability, we only model semaphores that take a finite range of values. If this range is exceeded then we regard this as an ERROR. N is the initial value. const Max = 3 range Int = 0..Max SEMAPHORE(N=0) = SEMA[N], SEMA[v:Int] = (up->sema[v+1] when(v>0) down->sema[v-1] ), SEMA[Max+1] = ERROR. LTS? 18

modeling semaphores up up up -1 0 1 2 3 down down down Action down is only accepted when value v of the semaphore is greater than 0. Action up is not guarded. up Trace to a violation: up à up à up à up 19

semaphore demo - model Three processes p[1..3] use a shared semaphore mutex to ensure mutually exclusive access (action critical) to some resource. LOOP = (mutex.down->critical->mutex.up->loop). SEMADEMO = (p[1..3]:loop {p[1..3]::mutex:semaphore(1)). For mutual exclusion, the semaphore initial value is 1. Why? Is the ERROR state reachable for SEMADEMO? Is a binary semaphore sufficient (i.e. Max=1)? LTS? 20

semaphore demo - model p.1.mutex.down p.2.mutex.down p.3.mutex.down p.3.critical p.2.critical p.1.critical 0 1 2 3 4 5 6 p.3.mutex.up p.2.mutex.up p.1.mutex.up 21

semaphores in Java Semaphores are passive objects, therefore implemented as monitors. (NOTE: In practice, semaphores are a low-level mechanism often used for implementing the higher-level monitor construct. Java SE5 provides general counting semaphores) public class Semaphore { private int value; public Semaphore (int initial) {value = initial; synchronized public void up() { ++value; notifyall(); synchronized public void down() throws InterruptedException { while (value== 0) wait(); --value; 22

SEMADEMO display current semaphore value thread 1 is executing critical actions. thread 2 is blocked waiting. thread 3 is executing non-critical actions. 23

SEMADEMO What if we adjust the time that each thread spends in its critical section? large resource requirement - more conflict? (eg. more than 67% of a rotation)? small resource requirement - no conflict? (eg. less than 33% of a rotation)? Hence the time a thread spends in its critical section should be kept as short as possible. 24

SEMADEMO program - revised ThreadPanel class public class ThreadPanel extends Panel { // construct display with title and rotating arc color c public ThreadPanel(String title, Color c) { // hasslider == true creates panel with slider public ThreadPanel (String title, Color c, boolean hasslider) { // rotate display of currently running thread 6 degrees // return false when in initial color, return true when in second color public static boolean rotate() throws InterruptedException { // rotate display of currently running thread by degrees public static void rotate(int degrees) throws InterruptedException { // create a new thread with target r and start it running public void start(runnable r) { // stop the thread using Thread.interrupt() public void stop() { 25

SEMADEMO program - MutexLoop class MutexLoop implements Runnable { Semaphore mutex; MutexLoop (Semaphore sema) {mutex=sema; public void run() { try { while(true) { while(!threadpanel.rotate()); mutex.down(); // get mutual exclusion while(threadpanel.rotate()); //critical actions mutex.up(); //release mutual exclusion catch(interruptedexception e){ Threads and semaphore are created by the applet start() method. ThreadPanel.rotate() returns false while executing non-critical actions (dark color) and true otherwise. 26

5.3 Bounded Buffer A bounded buffer consists of a fixed number of slots. Items are put into the buffer by a producer process and removed by a consumer process. It can be used to smooth out transfer rates between the producer and consumer. (see car park example) 27

bounded buffer - a data-independent model BOUNDEDBUFFER PRODUCER put BUFFER get CONSUMER The behaviour of BOUNDEDBUFFER is independent of the actual data values, and so can be modelled in a data-independent manner. LTS: put put put put put 0 1 2 3 4 5 get get get get get 28

bounded buffer - a data-independent model BUFFER(N=5) = COUNT[0], COUNT[i:0..N] = (when (i<n) put->count[i+1] when (i>0) get->count[i-1] ). PRODUCER = (put->producer). CONSUMER = (get->consumer). BOUNDEDBUFFER = (PRODUCER BUFFER(5) CONSUMER). 29

bounded buffer program - buffer monitor public interface Buffer <E> { We separate the class BufferImpl <E> implements Buffer <E> { interface to permit an public synchronized void put(e o) alternative throws InterruptedException { implementation while (count==size) wait(); buf[in] = o; ++count; in=(in+1)%size; later. notifyall(); public synchronized E get() throws InterruptedException { while (count==0) wait(); E o =buf[out]; buf[out]=null; --count; out=(out+1)%size; notifyall(); return (o); 30

bounded buffer program - producer process class Producer implements Runnable { Buffer buf; String alphabet= "abcdefghijklmnopqrstuvwxyz"; Producer(Buffer b) {buf = b; public void run() { try { int ai = 0; while(true) { ThreadPanel.rotate(12); buf.put(alphabet.charat(ai)); ai=(ai+1) % alphabet.length(); ThreadPanel.rotate(348); catch (InterruptedException e){ Similarly Consumer which calls buf.get(). 31

5.4 Nested Monitors Suppose that, in place of using the count variable and condition synchronization directly, we instead use two semaphores full and empty to reflect the state of the buffer. class SemaBuffer <E> implements Buffer <E> { Semaphore full; //counts number of items Semaphore empty; //counts number of spaces SemaBuffer(int size) { this.size = size; buf =(E[])new Object[size]; full = new Semaphore(0); empty= new Semaphore(size); 32

nested monitors - bounded buffer program synchronized public void put(e o) throws InterruptedException { empty.down(); buf[in] = o; ++count; in=(in+1)%size; full.up(); synchronized public E get() throws InterruptedException{ full.down(); E o =buf[out]; buf[out]=null; --count; out=(out+1)%size; empty.up(); return (o); Does this behave as desired? empty is decremented during a put operation, which is blocked if empty is zero; full is decremented by a get operation, which is blocked if full is zero. 33

nested monitors - bounded buffer model const Max = 5 range Int = 0..Max SEMAPHORE...as before... BUFFER = (put -> empty.down ->full.up ->BUFFER get -> full.down ->empty.up ->BUFFER ). PRODUCER = (put -> PRODUCER). CONSUMER = (get -> CONSUMER). BOUNDEDBUFFER = (PRODUCER BUFFER CONSUMER empty:semaphore(5) full:semaphore(0) )@{put,get. Does this behave as desired? 34

nested monitors - bounded buffer model LTSA analysis predicts a possible DEADLOCK: Composing potential DEADLOCK States Composed: 28 Transitions: 32 in 60ms Trace to DEADLOCK: get The Consumer tries to get a character, but the buffer is empty. It blocks and releases the lock on the semaphore full. The Producer tries to put a character into the buffer, but also blocks. Why? This situation is known as the nested monitor problem. 35

nested monitors - bounded buffer model synchronized public Object get() throws InterruptedException{ full.down(); // if no items, block!... get down full buffer wait put empty 36

nested monitors - revised bounded buffer program The only way to avoid it in Java is by careful design. In this example, the deadlock can be removed by ensuring that the monitor lock for the buffer is not acquired until after semaphores are decremented. public void put(e o) throws InterruptedException { empty.down(); synchronized(this){ buf[in] = o; ++count; in=(in+1)%size; full.up(); 37

nested monitors - revised bounded buffer model BUFFER = (put -> BUFFER get -> BUFFER ). PRODUCER =(empty.down->put->full.up->producer). CONSUMER =(full.down->get->empty.up->consumer). The semaphore actions have been moved to the producer and consumer. This is exactly as in the implementation where the semaphore actions are outside the monitor. Does this behave as desired? Minimized LTS? 38

5.5 Monitor invariants An invariant for a monitor is an assertion concerning the variables it encapsulates. This assertion must hold whenever there is no thread executing inside the monitor i.e. on thread entry to and exit from a monitor. CarParkControl Invariant: 0 spaces N Semaphore Invariant: Buffer Invariant: 0 value 0 count size and 0 in < size and 0 out< size and in = (out + count) modulo size Invariants can be helpful in reasoning about correctness of monitors using a logical proof-based approach. Generally we prefer to use a model-based approach amenable to mechanical checking. 39

5.6 Java Concurrency Utilities Package java.util.concurrent includes semaphores, and explicit locks with multiple condition variables. Monitors: implicit lock associated with each object, with methods wait(), notify() and notifyall() Lock interface: explicit lock objects, with methods lock(), unlock(), trylock(), and newcondition() Condition objects: explicit lock synchronization objects, with methods await(), signal() and signalall() Conditions gives the effect of having multiple wait-sets per object. 40

bounded buffer explicit lock with separate conditions class BufferImpl <E> implements Buffer <E> { final Lock buflock = new ReentrantLock(); final Condition notfull = buflock.newcondition(); final Condition notempty = buflock.newcondition(); public void put(e o) throws InterruptedException { buflock.lock(); try {while (count==size) notfull.await(); buf[in] = o; ++count; in=(in+1)%size; notempty.signalall(); finally {buflock.unlock(); public E get() throws InterruptedException { buflock.lock(); try {while (count==0) notempty.await(); E o =buf[out]; buf[out]=null;--count;out=(out+1)%size; notfull.signalall(); return (o); finally {buflock.unlock(); notfull and notempty are conditions associated with buflock. Processes wait separately: producers on notfull and consumers on 41 notempty.

Summary u Concepts l monitors: encapsulated data + access procedures mutual exclusion + condition synchronization l nested monitors u Model l guarded actions u Practice l monitors: private data and synchronized methods in Java l wait(), notify() and notifyall() for condition synchronization l single thread active in the monitor at a time 42