1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

Operating Systems Part III: Process Management (Process Synchronization)
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Chapter 6 Process Synchronization Bernard Chen Spring 2007.
Chapter 6: Process Synchronization
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Operating Systems CMPSC 473 Mutual Exclusion Lecture 13: October 12, 2010 Instructor: Bhuvan Urgaonkar.
Concurrency (3) CSE 132. iClicker/WUTexter Question The following four numbers are in 8-bit 2’s complement form: Which.
1 Lecture 18 Further Threading Overview  Case Study: Cooperating Threads  Producer/ Consumer model threads  Waiting for Synchronized Data  Busy Waiting.
Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
28-Jun-15 Producer-Consumer An example of using Threads.
Definitions Process – An executing program
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Operating Systems CSE 411 CPU Management Oct Lecture 13 Instructor: Bhuvan Urgaonkar.
Internet Software Development More stuff on Threads Paul Krause.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
6.3 Peterson’s Solution The two processes share two variables: Int turn; Boolean flag[2] The variable turn indicates whose turn it is to enter the critical.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Internet Software Development Controlling Threads Paul J Krause.
Producer-Consumer Problem The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue.bufferqueue.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Synchronizing threads, thread pools, etc.
Kernel Locking Techniques by Robert Love presented by Scott Price.
1 G53SRP: Java Concurrency Control (1) - synchronisation Chris Greenhalgh School of Computer Science.
CY2003 Computer Systems Lecture 04 Interprocess Communication.
Chapter 6 – Process Synchronisation (Pgs 225 – 267)
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
1 G53SRP: Clocks and Time in Java Chris Greenhalgh School of Computer Science.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
1 Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois.
Operating Systems CSE 411 CPU Management Dec Lecture Instructor: Bhuvan Urgaonkar.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
6.1 Silberschatz, Galvin and Gagne ©2005 Operating System Principles 6.5 Semaphore Less complicated than the hardware-based solutions Semaphore S – integer.
Multithreading / Concurrency
Background on the need for Synchronization
Lecture 24 Concurrency 2 (D&D 23) Date.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Monitors Chapter 7.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Multithreading.
Java Concurrency 17-Jan-19.
Monitors Chapter 7.
Monitors Chapter 7.
Java Concurrency.
Java Concurrency.
Java Concurrency 29-May-19.
Software Engineering and Architecture
Presentation transcript:

1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science

2 Contents Wait/notify overviewWait/notify overview Wait()Wait() Notify()Notify() Infinite bufferInfinite buffer General concurrency controlGeneral concurrency control Reader/writer lockReader/writer lock Timed waitTimed wait SummarySummary Book: Wellings 3.2Book: Wellings 3.2

3 Wait/notify Overview Every Java object has a wait queue as well as a lockEvery Java object has a wait queue as well as a lock Only a thread holding the lock can manipulate the wait queueOnly a thread holding the lock can manipulate the wait queue The queue is manipulated using the java.lang.Object methods wait(…) and notify() / notifyAll() …The queue is manipulated using the java.lang.Object methods wait(…) and notify() / notifyAll() … –All classes extend java.lang.Object Lock Object Wait queue Method… wait notify

4 wait() A thread calling wait is added to the wait queueA thread calling wait is added to the wait queue –(not necessarily the end) It releases the object lock while waitingIt releases the object lock while waiting It re-obtains the object lock before returningIt re-obtains the object lock before returning Why use wait?Why use wait? –Efficient task cooperation (avoids polling and avoids race conditions or lock-out with sleep)

5 Wait detail … synchronized (this) { try { this.wait();… synchronized (this) { try { this.wait(); } catch (InterruptedException ie) { } } } catch (InterruptedException ie) { } } Gains lock on ‘this’ Releases lock on ‘this’ Thread has lock has lock Added to wait queue (time passes) Woken from wait queue (time passes) Re-gains lock on ‘this’

6 notify() A thread calling notify() wakes one thread(s) from the wait queueA thread calling notify() wakes one thread(s) from the wait queue A thread calling notifyAll() wakes all thread(s) from the wait queueA thread calling notifyAll() wakes all thread(s) from the wait queue If there are no threads waiting then the calls have no effectIf there are no threads waiting then the calls have no effect –Notifies are not “queued” or “persistent” Waiting threads are not subdivided or classifiedWaiting threads are not subdivided or classified –Notify cannot wake a certain kind of thread or method –=> less efficient than some alternative

7 Infinite buffer Class Buffer { Vector data = new Vector (); Vector data = new Vector (); synchronized void put(T item) { synchronized void put(T item) { data.add(item); data.add(item); notify(); notify(); } … … public synchronized T get() { while (data.size()==0) { try { wait(); } catch(InterruptedException ie) {} } T item = data.get(0); data.remove(0); return item; } has lock has lock wakes

8 Infinite buffer - cases get(), data in bufferget(), data in buffer –Removes and returns first item get(), no data in bufferget(), no data in buffer –Waits until data present put(), no thread waitingput(), no thread waiting –Add data to buffer (notify is no-op) put(), thread(s) waitingput(), thread(s) waiting –Add data to buffer, wake one thread

9 Infinite buffer - notes notify() may wake any waiting threadnotify() may wake any waiting thread –But only threads calling get ever wait Put only adds one itemPut only adds one item –only one waiting thread can now take this item, so only needs to be woken up wait() may terminate due to interruptwait() may terminate due to interrupt A waiting thread may be beaten to the lock by a new get() threadA waiting thread may be beaten to the lock by a new get() thread –E.g. if it was already waiting to obtain the lock –So it has to be ready to wait more than once!

10 General concurrency control Thread 1Thread 1 –…–…–…–… –Entry protocol –Critical section –Exit protocol –…–…–…–… Entry:Entry: –Block until safe to proceed (update state) Thread 2 –…–… –Entry protocol –Critical section –Exit protocol –…–… Exit: –(update state) Wake any blocked threads now able to proceed

11 Infinite buffer revisited Class Buffer { Vector data = new Vector (); Vector data = new Vector (); synchronized void put(T item) { synchronized void put(T item) { data.add(item); data.add(item); notify(); notify(); } … … public synchronized T get() { while (data.size==0) { try { wait(); } catch(InterruptedException ie) {} } T item = data.get(0); data.remove(0); return item; } entry exit Critical section

12 Infinite buffer notes Object lock is held during critical sectionObject lock is held during critical section –So at most one thread can be in critical section If more than one thread should be in critical section then lock must be released and regainedIf more than one thread should be in critical section then lock must be released and regained –E.g. separate into two synchronized blocks

13 Synchronized method implementation This:… synchronized void method() { …}… static synchronized void method() { …} Equals: … void method() { synchronized (this) { … } … static void method() { synchronized (ThisClass.class) { … }

14 Reader/writer lock - specification Shared lock objectShared lock object In critical section can be:In critical section can be: –Any number of reader threads OR –Only one writer thread

15 Reader/writer lock - state Class ReaderWriterLock { int writers = 0; int writers = 0; int readers = 0; int readers = 0; …} Could be boolean

16 Reader entry protocol public synchronized void readerEntry() { while (writers>0) { while (writers>0) { try { try { wait(); wait(); } catch (InterruptedException ie) {} } catch (InterruptedException ie) {} } readers++; readers++;} N.B. mutual exclusion required (synchronized!) Update state Condition

17 Writer entry protocol public synchronized void writerEntry() { while (writers>0 || readers>0) { while (writers>0 || readers>0) { try { try { wait(); wait(); } catch (InterruptedException ie) {} } catch (InterruptedException ie) {} } writers++; writers++;}

18 Reader exit protocol public synchronized void readerExit() { readers--; readers--; if (readers==0) if (readers==0) notify(); notify();} Wake one thread (if a reader was running no Reader should have been waiting) Update state Could use notifyAll() would be safer because ____________________ but_____________________________

19 Writer exit protocol public synchronized void writerExit() { writers--; writers--; notifyAll(); notifyAll();} Wake all threads (there may be several readers waiting) Update state

20 Reader/writer lock notes What happens if calls to entry/exit are not matched?What happens if calls to entry/exit are not matched? –Enter without exit? Deadlock, as lock never released –Exit without enter? Error or incorrect admission of concurrent threads

21 Timed wait() wait() waits indefinitelywait() waits indefinitely –Or until interrupted wait(long millis) waits at most millis ms before attempted to regain lock & continuewait(long millis) waits at most millis ms before attempted to regain lock & continue –But wait(0) waits indefinitely –Cannot tell if timed out or notified! Allows time-outAllows time-out –E.g. error or deadlock detection

22 Summary Each object has a wait queue as well as a lockEach object has a wait queue as well as a lock –= “monitor” wait() blocks a thread and releases the lock until notify() / notifyAll()wait() blocks a thread and releases the lock until notify() / notifyAll() Supports general concurrency controlSupports general concurrency control –Can be used to avoid busy waiting or polling Additional variable(s) are required to track concurrency requirementsAdditional variable(s) are required to track concurrency requirements