Monitors 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

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
CS 11 java track: lecture 7 This week: Web tutorial:
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
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.
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.
Definitions Process – An executing program
Garbage Collection CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
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.
Methods CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads some important concepts Simon Lynch
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
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.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
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.
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.
Multi-Threaded Programming Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Internet Software Development Controlling Threads Paul J Krause.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
Synchronizing threads, thread pools, etc.
Parallel Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Program5 Due Friday, March Prog4 user_thread... amount = … invoke delegate transact (amount)... mainThread... Total + = amount … user_thread...
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
Java Thread and Memory Model
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.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
Semaphores CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Classes CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Principles of Software Development
Multithreading / Concurrency
Multi Threading.
Multithreading.
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
CS203 Lecture 15.
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

Outline USC CSCI 201L2/16 ▪M▪Monitors

Monitor Overview ▪A monitor is an object with mutual exclusion and synchronization capabilities ›All objects in Java can be monitors ▪The synchronized keyword enables the use of monitors ›Methods or individual blocks of code in Java can be synchronized ▪A thread enters the monitor by acquiring a lock on it and exits by releasing the lock ▪An object becomes a monitor once a thread locks it using the synchronized keyword ▪A thread can call wait() inside a monitor, which will release the lock on the object ›That thread must then be awakened using notify() or notifyAll() from another thread to be moved back into the Ready state USC CSCI 201L3/16 Monitors

synchronized Keyword ▪The synchronized keyword puts a restriction on a method or block of code that only one thread can be inside that method or block at a time ›No other thread will be able to enter that method or block of code if another thread is currently executing inside of it, regardless of whether it is in the CPU currently or not ▪Before a block of synchronized code can execute, a lock must be obtained ›A lock is a binary mechanism for exclusive use of a resource ›Locks can only be acquired by one object at a time USC CSCI 201L4/16 Monitors

synchronized Methods ▪synchronized Non-Static Methods ›The lock obtained is on the object on which the method was invoked ›When a thread invokes a synchronized instance method of an object, the lock of that object is acquired first, then the method is executed, then the lock is released Another thread invoking any synchronized method or block of code on that object is blocked until the lock is released ▪synchronized Static Methods ›The lock obtained is on the class on which the method was invoked (even if the method was invoked from an instance of the class, which would be bad programming) ›When a thread invokes a synchronized static method of a class, the lock on that class is acquired first, then the method is executed, then the lock is released Another thread invoking any synchronized method or block of code on that class is blocked until the lock is released USC CSCI 201L5/16 Monitors

Synchronization Example #1 1 class SyncClass { 2 synchronized void foo() { 3 // foo line 1 4 // foo line 2 5 } 6 synchronized void bar() { 7 // bar line 1 8 // bar line 2 9 } 10 void meth() { 11 // meth line 1 12 // meth line 2 13 } 14 } public class MainClass { 17 public static void main(String [] args) { 18 SyncClass sc = new SyncClass(); 19 // multiple threads created 20 } 21 } USC CSCI 201L6/16 Monitors Thread T1 calls sc.foo(); and gets switched out of the CPU after line 3 Thread T2 calls sc.foo(); Will T2 be able to execute?

Synchronization Example #2 1 class SyncClass { 2 synchronized void foo() { 3 // foo line 1 4 // foo line 2 5 } 6 synchronized void bar() { 7 // bar line 1 8 // bar line 2 9 } 10 void meth() { 11 // meth line 1 12 // meth line 2 13 } 14 } public class MainClass { 17 public static void main(String [] args) { 18 SyncClass sc = new SyncClass(); 19 // multiple threads created 20 } 21 } USC CSCI 201L7/16 Monitors Thread T1 calls sc.foo(); and gets switched out of the CPU after line 3 Thread T2 calls sc.bar(); Will T2 be able to execute?

Synchronization Example #3 1 class SyncClass { 2 synchronized void foo() { 3 // foo line 1 4 // foo line 2 5 } 6 synchronized void bar() { 7 // bar line 1 8 // bar line 2 9 } 10 void meth() { 11 // meth line 1 12 // meth line 2 13 } 14 } public class MainClass { 17 public static void main(String [] args) { 18 SyncClass sc = new SyncClass(); 19 SyncClass sc2 = new SyncClass(); 20 // multiple threads created 21 } 22 } USC CSCI 201L8/16 Monitors Thread T1 calls sc.foo(); and gets switched out of the CPU after line 3 Thread T2 calls sc2.foo(); Will T2 be able to execute?

Synchronization Example #4 1 class SyncClass { 2 static synchronized void foo() { 3 // foo line 1 4 // foo line 2 5 } 6 static synchronized void bar() { 7 // bar line 1 8 // bar line 2 9 } 10 void meth() { 11 // meth line 1 12 // meth line 2 13 } 14 } public class MainClass { 17 public static void main(String [] args) { 18 SyncClass sc = new SyncClass(); 19 SyncClass sc2 = new SyncClass(); 19 // multiple threads created 20 } 21 } USC CSCI 201L9/16 Monitors Thread T1 calls sc.foo(); and gets switched out of the CPU after line 3 Thread T2 calls sc2.bar(); Will T2 be able to execute?

Synchronization Example #5 1 class SyncClass { 2 static synchronized void foo() { 3 // foo line 1 4 // foo line 2 5 } 6 static synchronized void bar() { 7 // bar line 1 8 // bar line 2 9 } 10 void meth() { 11 // meth line 1 12 // meth line 2 13 } 14 } public class MainClass { 17 public static void main(String [] args) { 18 SyncClass sc = new SyncClass(); 19 SyncClass sc2 = new SyncClass(); 19 // multiple threads created 20 } 21 } USC CSCI 201L10/16 Monitors Thread T1 calls SyncClass.foo(); and gets switched out of the CPU after line 3 Thread T2 calls SyncClass.bar(); Will T2 be able to execute?

Synchronization Example #6 1 class SyncClass { 2 static synchronized void foo() { 3 // foo line 1 4 // foo line 2 5 } 6 synchronized void bar() { 7 // bar line 1 8 // bar line 2 9 } 10 void meth() { 11 // meth line 1 12 // meth line 2 13 } 14 } public class MainClass { 17 public static void main(String [] args) { 18 SyncClass sc = new SyncClass(); 19 SyncClass sc2 = new SyncClass(); 19 // multiple threads created 20 } 21 } USC CSCI 201L11/16 Monitors Thread T1 calls SyncClass.foo(); and gets switched out of the CPU after line 3 Thread T2 calls sc2.bar(); Will T2 be able to execute?

synchronized Statements ▪We do not need to synchronize entire methods if only a part of the method needs to be synchronized ▪A synchronized statement can be used to acquire a lock on any object, not just the current object synchronized(obj) { // synchronized code } ▪The lock would have to be obtained on the object obj before the code in that block could execute ›If the lock cannot be obtained, the thread will block at that line until it can obtain the lock ▪Note that any synchronized method can be converted into a synchronized block of code public synchronized void meth() {public void meth() { // code synchronized(this) { } // code } USC CSCI 201L12/16 Monitors

AddAPenny Example Revisited 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()) { 19 Thread.yield(); 20 } System.out.println("Balance = " + piggy.getBalance()); 23 } 24 } class PiggyBank { 27 private int balance = 0; 28 public int getBalance() { 29 return balance; 30 } 31 public void deposit(int amount) { 32 int newBalance = balance + amount; 33 Thread.yield(); 34 balance = newBalance; 35 } 36 } USC CSCI 201L13/16 Monitors 4 Executions

AddAPenny with Synchronization 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()) { 19 Thread.yield(); 20 } System.out.println("Balance = " + piggy.getBalance()); 23 } 24 } class PiggyBank { 27 private int balance = 0; 28 public int getBalance() { 29 return balance; 30 } 31 public synchronized void deposit(int amount) { 32 int newBalance = balance + amount; 33 Thread.yield(); 34 balance = newBalance; 35 } 36 } USC CSCI 201L14/16 Monitors 4 Executions

Outline USC CSCI 201L15/16 ▪M▪Monitors ▪P▪Program

Program ▪Download the AddAndRemoveAPenny code from the course web site and execute it ›Make sure you understand why the output is what it is ▪What modification could you make to the code to force it to hang if the total amount of withdrawals exceeds the total amount of deposits? ▪Modify the code to remove having an equal number of threads that withdraw and deposit ›Does the code always terminate in either case? ›How can you make the code always terminate? USC CSCI 201L16/16 Program