Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

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.
1Deadlock DeadlockedBankAccount –withdraw(){ lock.lock(); while(balance
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 24 Multithreading.
Li Tak Sing (Lecture 3) COMPS311F 1. Flexible synchronization with locks Synchronized methods and statement blocks: Advantages: Relatively easy to use.
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.
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.
CS 11 java track: lecture 7 This week: Web tutorial:
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L21 (Chapter 24) Multithreading.
Programming in Java; Instructor:Alok Mehta Threads1 Programming in Java Threads.
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.
Garbage Collection CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Methods CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
CSE 219 Computer Science III Multithreaded Issues.
Threads some important concepts Simon Lynch
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
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.
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.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Multi-Threaded Programming Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Parallel Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 G53SRP: Java Concurrency Control (1) - synchronisation Chris Greenhalgh School of Computer Science.
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]
Multithreading in JAVA
Java Thread and Memory Model
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CMSC 330: Organization of Programming Languages Threads.
Semaphores CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Classes CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
Thread Pools CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
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.
Multithreading. DCS – SWC 2 What is a thread Inside a single process, multiple threads can be executing concurrently A thread is the execution of (part.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Principles of Software Development
CSCD 330 Network Programming
Multithreading / Concurrency
Chapter 30 Multithreading and Parallel Programming
Multithreading.
Threads Chate Patanothai.
Principles of Software Development
Thread Synchronization
Principles of Software Development
Multithreading.
CS203 Lecture 15.
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L

Outline USC CSCI 201L2/9 ▪L▪Locks ›L›Lock Conditions

synchronized Keyword ▪The synchronized keyword puts a restriction on a method that only one thread can be inside at a time ›This is accomplished using a monitor ›No other thread will be able to enter that method if another thread is currently executing inside of it, regardless of whether it is in the CPU currently or not USC CSCI 201L3/9 Locks

Explicitly Acquiring Locks ▪A synchronized method or block of code implicitly acquires a lock on the instance before executing ▪Java gives us the ability to explicitly acquire locks using the java.util.concurrent.locks.Lock interface and java.util.concurrent.locks.ReentrantLock class USC CSCI 201L4/9 Locks

synchronized Keyword Example 1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 4 public class AddAPenny implements Runnable { 5 private static PiggyBank piggy = new PiggyBank(); 6 7 public void run() { 8 piggy.deposit(1); 9 } public static void main(String [] args) { 12 ExecutorService executor = Executors.newCachedThreadPool(); 13 for (int i=0; i < 100; i++) { 14 executor.execute(new AddAPenny()); 15 } 16 executor.shutdown(); 17 // wait until all tasks are finished 18 while(!executor.isTerminated()) { } System.out.println("Balance = " + piggy.getBalance()); 21 } 22 } class PiggyBank { 25 private int balance = 0; 26 public int getBalance() { 27 return balance; 28 } 29 public synchronized void deposit(int amount) { 30 int newBalance = balance + amount; 31 Thread.yield(); 32 balance = newBalance; 33 } 34 } USC CSCI 201L5/9 Locks 4 Executions

Explicitly Acquiring Locks Example 1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 import java.util.concurrent.locks.Lock; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 public class AddAPenny implements Runnable { 7 private static PiggyBank piggy = new PiggyBank(); 8 9 public void run() { 10 piggy.deposit(1); 11 } public static void main(String [] args) { 14 ExecutorService executor = Executors.newCachedThreadPool(); 15 for (int i=0; i < 100; i++) { 16 executor.execute(new AddAPenny()); 17 } 18 executor.shutdown(); 19 // wait until all tasks are finished 20 while(!executor.isTerminated()) { } System.out.println("Balance = " + piggy.getBalance()); 23 } 24 } class PiggyBank { 27 private int balance = 0; 28 private Lock lock = new ReentrantLock(); 29 public int getBalance() { 30 return balance; 31 } 32 public void deposit(int amount) { 33 lock.lock(); 34 try { 35 int newBalance = balance + amount; 36 Thread.yield(); 37 balance = newBalance; 38 } finally { 39 lock.unlock(); 40 } 41 } 42 } USC CSCI 201L6/9 Locks 4 Executions

Thread Conditions ▪Threads are able to communicate with each other based on specific conditions ▪Threads can perform the following actions using the java.util.concurrent.Condition interface ›await() Wait for the condition to be signaled ›signal() Wake up one thread waiting on the condition ›signalAll() Wake up all of the threads waiting on the condition ▪A Condition is created from a Lock object by calling the newCondition() method USC CSCI 201L7/9 Locks – Lock Conditions

Thread Conditions Example 1 import java.util.concurrent.ExecutorService; 2 import java.util.concurrent.Executors; 3 import java.util.concurrent.locks.Condition; 4 import java.util.concurrent.locks.Lock; 5 import java.util.concurrent.locks.ReentrantLock; 6 7 public class AddAndRemoveAPenny implements Runnable { 8 private static PiggyBank piggy = new PiggyBank(); 9 private boolean isWithdrawal; public void run() { 12 if (isWithdrawal) { 13 piggy.deposit((int)(Math.random() * 9 + 1)); 14 } 15 else { 16 piggy.withdraw((int)(Math.random() * 9 + 1)); 17 } 18 } public static void main(String [] args) { 21 ExecutorService executor = Executors.newCachedThreadPool(); 22 for (int i=0; i < 100; i++) { 23 AddAndRemoveAPenny penny = new AddAndRemoveAPenny(); 24 if (i < 50) { // exactly 50 threads will withdraw 25 penny.isWithdrawal = false; 26 } 27 else { // and exactly 50 threads will deposit 28 penny.isWithdrawal = true; 29 } 30 executor.execute(penny); 31 } 32 executor.shutdown(); 33 // wait until all tasks are finished 34 while(!executor.isTerminated()) { } System.out.println("Balance = " + piggy.getBalance()); 37 } 38 } USC CSCI 201L8/9 Locks – Lock Conditions 39 class PiggyBank { 40 private int balance = 0; 41 private Lock lock = new ReentrantLock(); 42 private Condition depositMade = lock.newCondition(); 43 public int getBalance() { 44 return balance; 45 } 46 public void withdraw(int amount) { 47 lock.lock(); 48 try { 49 while (balance < amount) { 50 System.out.print("Waiting for deposit...”); 51 System.out.print(“ to withdraw $" + amount); 52 System.out.println(" from balance of $" + balance); 53 depositMade.await(); 54 } 55 balance -= amount; 56 System.out.print("$" + amount + " withdrawn,”); 57 System.out.println(“ leaving balance of $" + balance); 58 } catch (InterruptedException ie) { 59 System.out.println("IE: " + ie.getMessage()); 60 } finally { 61 lock.unlock(); 62 } 63 } 64 public void deposit(int amount) { 65 lock.lock(); // acquires lock 66 try { 67 balance += amount; 68 System.out.print("$" + amount + " deposited,”); 69 System.out.println(“ making balance of $" + balance); 70 depositMade.signalAll(); 71 } finally { 72 lock.unlock(); // release the lock 73 } 74 } 75 }

Thread Conditions Issues ▪Once a thread invokes await() on a condition, the thread will move to the waiting state until it is signaled ›If signal() or signalAll() is never called on the condition, the thread will wait forever ›In the previous example, some executions of the program never terminate if a withdrawal was not able to be made based on the balance after all the deposits were made ▪You must first obtain the lock on the object before you are able to invoke a method on its Condition ›When a thread calls await(), it will release its lock It will not be able to start executing again, even after it is signaled, if it is not able to obtain the lock again USC CSCI 201L9/9 Locks – Lock Conditions