1Deadlock DeadlockedBankAccount –withdraw(){ lock.lock(); while(balance <= 0){ System.out.print("W"); // waiting for the balance to exceed 0 Thread.sleep(1000);

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

Ken Birman 1. Refresher: Dekers Algorithm Assumes two threads, numbered 0 and 1 CSEnter(int i) { int J = i^1; inside[i] = true; turn = J; while(inside[J]
Monitors & Blocking Synchronization 1. Producers & Consumers Problem Two threads that communicate through a shared FIFO queue. These two threads can’t.
CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
1 Race Conditions When threads share access to a common object/data, they can conflict with each other and mess up the consistency of the object/data.
1 Java threads: synchronization. 2 Thread states 1.New: created with the new operator (not yet started) 2.Runnable: either running or ready to run 3.Blocked:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 24 Multithreading.
Multi-Threading Dr. M. Khamis. Thread-Based Multi-Tasking Thread-based multi-tasking is about a single program executing concurrently several tasks e.g.
Li Tak Sing (Lecture 3) COMPS311F 1. Flexible synchronization with locks Synchronized methods and statement blocks: Advantages: Relatively easy to use.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  synchronized methods and statements  wait.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Multithreading. RHS – SWC 2 What is a thread Inside a single process, multiple threads can be executing concurrently A thread is the execution of (part.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Concurrency (3) CSE 132. iClicker/WUTexter Question The following four numbers are in 8-bit 2’s complement form: Which.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Monitors and Blocking Synchronization By Tal Walter.
1Quiz Modify HelloWorld2.java; –Remove (or comment out) the following 4 lines: Thread thread1 = new Thread(runnable1); Thread thread2 = new Thread(runnable2);
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
Semaphores, mutexes and condition variables. semaphores Two types – Binary – 0 or 1 – Counting 0 to n Wait – decrements > 0 forces a wait Post or signal.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L21 (Chapter 24) Multithreading.
1 What is the “volatile” Keyword? You can skip locking (thread synchronization) in some cases by using the volatile variables. –No locking/unlocking =
1 Concurrency: Deadlock and Starvation Chapter 6.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
ThreadThread Thread Basics Thread Synchronization Animations.
1Semaphore A special type of lock. –Similar to lock as it can be used to prevent access to shared data when the data is locked. –A lock that has a value.
Concurrency: Deadlock and Starvation Chapter 6. Goal and approach Deadlock and starvation Underlying principles Solutions? –Prevention –Detection –Avoidance.
1 Concurrency: Deadlock and Starvation Chapter 6.
Chapter 21 – Multithreading Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Internet Software Development More stuff on Threads Paul Krause.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Threading Eriq Muhammad Adams J
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
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.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
3/17/2016cse synchronization-p2 © Perkins, DW Johnson and University of Washington1 Synchronization Part 2 CSE 410, Spring 2008 Computer.
Producer/Consumer CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multithreading (Based on Chapter 29 (Multithreading) Liang book and Chapter 5 (Threads) Elliotte Rusty book) Dr. Tatiana Balikhina 1.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
Distributed and Parallel Processing George Wells.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Multithreading / Concurrency
Chapter 30 Multithreading and Parallel Programming
COEN346 Tutorial Monitor Objects.
Multithreading Chapter 9.
Threads Chate Patanothai.
Multithreading Chapter 23.
Thread Synchronization
Lecture 9 Synchronization.
Threads and Multithreading
Presentation transcript:

1Deadlock DeadlockedBankAccount –withdraw(){ lock.lock(); while(balance <= 0){ System.out.print("W"); // waiting for the balance to exceed 0 Thread.sleep(1000); } balance -= amount; lock.unlock(); } –deposit(){ lock.lock(); while(balance > 10000){ System.out.print("W"); // waiting for the balance to go below Thread.sleep(1000) } balance += amount; lock.unlock(); }

2 Output: DeadlockedBankAccount Lock obtained Current balance (d): 0.0WWWWWWW

3DeadlockedBankAccount2 public void deposit(double amount){ while( balance > ){ System.out.print("W"); Thread.sleep(2); } lock.lock(); balance += amount; lock.unlock(); } public void withdraw(double amount){ while( balance <= 0 ){ System.out.print("W"); Thread.sleep(2); } lock.lock(); balance -= amount; lock.unlock(); }

4 Lock obtained WCurrent balance (d): 0.0, New balance (d): Lock released Lock obtained Current balance (w): 100.0, New balance (w): 0.0 Lock released Lock obtained Current balance (d): 0.0, New balance (d): Lock released Lock obtained Current balance (w): 100.0, New balance (w): 0.0 Lock released Lock obtained Current balance (d): 0.0, New balance (d): Lock released

5 Withdraw thread Deposit thread If(balance true print out “W” sleep Reaches the end of its time slice Gain a time slice Acquire a lock print(“current balance…); // 0 balance += amount; // balance --> 100 println(“new balance…); // 100 Release a lock Reaches the end of its time slice (balance=100) Gain a time slice If(balance false Withdraw money Lock obtained WCurrent balance (d): 0.0, New balance (d): Lock released

6 DeadlockBankAccount2 has no deadlock problems. However, it is not completely thread safe. Why?

7 Withdraw thread Deposit thread If(balance true Reaches the end of its time slice Gain a time slice Acquire a lock print(“current balance…); // 0 balance += amount; // balance --> 100 println(“new balance…); // 100 Release a lock Reaches the end of its time slice (balance=100) Gain a time slice print out “W” sleep() If(balance false Withdraw money These two lines are not supposed to be executed when balance > 0.

8 Avoiding Deadlocks Use Condition objects –Allow a thread to temporarily release a lock so that another thread can proceed –The thread goes to the Waiting state from the Runnable state. re-acquire the lock at a later time. java.util.concurrent.locks.Condition –Obtain its instance from a lock object private ReentrantLock lock; Condition condition = lock.newCondition(); condition.await();

9 Runnable Blocked new New start() I/O op completion or thread sync done I/O operation or wait for thread sync (lock) Terminated Exits run() or Explicit thread termination Waiting sleep() join() wait() await() notify() notifyAll() signalAll() interruption Timed Waiting sleep() join() wait() await() notify() notifyAll() signalAll() interruption

10ThreadSafeBankAccount2 Condition sufficientFundsCondition = lock.newCondition(); Condition belowUpperLimitFundsCondition = lock.newCondition(); withdraw(double amount){ lock.lock(); while(balance < amount){ // waiting for the balance to exceed “amount” sufficientFundsCondition.await(); } balance -= amount; lock.unlock(); belowUpperLimitFundsCondition.signalAll(); } deposit(double amount){ lock.lock(); while(balance >= 300){ // waiting for the balance to go below the upper limit. belowUpperLimitFundsCondition.await(); } balance += amount; lock.unlock(); sufficientFundsCondition.signalAll(); }

11Condition await() –Until it is signaled or interrupted –Until it is signaled or interrupted, or a specified waiting time (relative time) elapsed. –Until it is signaled or interrupted, or a specified deadline (absolute time) time elapsed. signalAll() –Wakes up all the threads waiting on this condition. –There is no guarantee about which thread will acquire a lock. signal() –Wakes up one of the threads waiting on this condition. –There is no guarantee about which thread is waked up.

12ThreadSafeBankAccount2 Output –Lock obtained –7 (d): current balance: 0.0 –7 (d): new balance: –Lock released –Lock obtained –8 (d): current balance: –8 (d): new balance: –Lock released –Lock obtained –9 (d): current balance: –9 (d): new balance: –Lock released –Lock obtained –10 (d): current balance: –10 (d): await(): Balance exceeds the upper limit. –Lock obtained –11 (d): current balance: –11 (d): await(): Balance exceeds the upper limit. –Lock obtained –12 (w): current balance: –12 (w): new balance: –Lock released –10 (d): new balance: –Lock released –11 (d): await(): Balance exceeds the upper limit.

13 Thread Synchronization Tools Lock (or mutex) –java.util.concurrent.locks.ReentrantLock Reader-writer locks –java.util.concurrent.locks.ReentrantReadWriteLock –java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock –java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock Semaphore –java.util.concurrent.Semaphore Barrier –java.util.concurrent.CyclicBarrier

14 Reader-Writer Locks Special types of lock Lock –Shared data must be locked when it is being changed/written. –Is data locking necessary among read-only threads? No. Read-only threads do not have to compete against each other to acquire a lock. Why not being nice or optimistic about data locking for readers?

15ReadWriteLock ReentrantReadWriteLock –In java.util.concurrent.locks ReentrantReadWriteLock{ public ReentrantReadWriteLock.ReadLock readLock(){} public ReentrantReadWriteLock.WriteLock writeLock(){} } –Provides two locks; a lock for writers, and the other for readers. Readers obtain a read lock. Writers obtain a write lock.

16 Readers can acquire a read lock even if it is already held by another reader, –AS FAR AS no writers holds a write lock. Writers can acquire a write lock ONLY IF no other writers and readers hold read/write locks. A thread trying to acquire a lock Other threads exist holding …? ReadLock WriteLock ReadLockWriteLock Y N N N

17 ReentrantReadWriteLock.ReadLock ReentrantReadWriteLock.WriteLock –Inner classes of ReentrantReadWriteLock They are used only by ReentrantReadWriteLock; they should not be open/available for anything else. –Work similarly to ReentrantLock. These locks support nested locking. A condition object is returned when calling newCondition() on a write lock. Calling newCondition() on a read lock generates an UnsupportedOperationException.

18 Sample Code ThradSafeBankAccount3 –43 msec ThradSafeBankAccount4 –33 msec 23% (10/43) faster

19 When to Use ReadWriteLock? When many readers run. When readers run more frequently than writers. When read operations take a long time.