Monitors CSCI 201 Principles of Software Development

Similar documents
Concurrency CSCI 201 Principles of Software Development

Producer/Consumer CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Multi-Threaded Programming Design CSCI 201 Principles of Software Development

Introduction to Java Threads

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CMSC 132: Object-Oriented Programming II

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Polymorphism CSCI 201 Principles of Software Development

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

CSCI 201L Written Exam #1 Fall % of course grade

Concurrent Computing CSCI 201 Principles of Software Development

Part IV Other Systems: I Java Threads

Chapter 32 Multithreading and Parallel Programming

Threads Chate Patanothai

Sharing is the Key. Lecture 25: Parallelism. Canonical Example. Bad Interleavings. Common to have: CS 62 Fall 2016 Kim Bruce & Peter Mawhorter

Synchronization in Java

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Parallel Computing CSCI 201 Principles of Software Development

Multithread Computing

Sleeping Barber CSCI 201 Principles of Software Development

What is a thread anyway?

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Parallel Programming Practice

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Parallel Programming Practice

CS 159: Parallel Processing

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

CSCD 330 Network Programming

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

CSCI 201L Written Exam #1 Fall % of course grade

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

Global variables and resources are shared between threads within the same process. Each thread has its own stack and program counter (see Fig 2-7).

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CS 556 Distributed Systems

Programmazione Avanzata e Paradigmi Ingegneria e Scienze Informatiche - UNIBO a.a 2013/2014 Lecturer: Alessandro Ricci

STUDENT LESSON A5 Designing and Using Classes

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

Faculty of Computers & Information Computer Science Department

Threads and Parallelism in Java

System Programming. Practical Session 4: Threads and Concurrency / Safety

Lecture 29: Java s synchronized statement

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Java Threads. COMP 585 Noteset #2 1

Writing Parallel Programs COMP360

Buch gefunden? Im Blackboard eingetragen? Abgabe 1. Übung: , 23:59

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Java Threads. Introduction to Java Threads

Synchronization

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Threads Synchronization

Networking Code CSCI 201 Principles of Software Development

Synchronization in Concurrent Programming. Amit Gupta

Multi-threading in Java. Jeff HUANG

COE518 Lecture Notes Week 7 (Oct 17, 2011)

Programming Java. Multithreaded Programming

CSCD 330 Network Programming

Programming Language Concepts: Lecture 11

CS5233 Components Models and Engineering

CSCI 201L Written Exam #2. 10% of course grade

Basics of. Multithreading in Java

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Lecture 9: Introduction to Monitors

CMSC 132: Object-Oriented Programming II. Threads in Java

Concurrent Programming using Threads

Parallel & Concurrent Programming

Module - 4 Multi-Threaded Programming

COMP346 Winter Tutorial 4 Synchronization Semaphores

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Monitors & Condition Synchronization

Synchronization. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University

Exam Number/Code : 1Z Exam Name: Name: Java Standard Edition 6. Demo. Version : Programmer Certified Professional Exam.

Chapter 19 Multithreading

Multiple Inheritance. Computer object can be viewed as

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

COMP30112: Concurrency Topics 4.1: Concurrency Patterns - Monitors

CST242 Concurrency Page 1

12% of course grade. CSCI 201L Final - Written Fall /7

Programming in Parallel COMP755

CSE332: Data Abstractions Lecture 19: Mutual Exclusion and Locking

ECE 462 Exam 3. 11:30AM-12:20PM, November 17, 2010

Synchronization I. Jo, Heeseung

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

public class Shared0 { private static int x = 0, y = 0;

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Lecture 9 Threading, Synchronization, Interruption. Manu Kumar

Synchronization COMPSCI 386

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 4 Shared-Memory Concurrency & Mutual Exclusion

Atomicity CS 2110 Fall 2017

10/17/ Gribble, Lazowska, Levy, Zahorjan 2. 10/17/ Gribble, Lazowska, Levy, Zahorjan 4

Internet and Intranet Protocols and Applications

Transcription:

Monitors CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu

Outline Monitors Program USC CSCI 201L

Monitor Overview A monitor is an object with mutual exclusion and synchronization capabilities All objects in Java can be monitors (see Object API on next slide) 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 has the monitor functionality invoked once a thread locks it using the synchronized keyword USC CSCI 201L 3/19

Object class 4/19

Monitor Overview The Object class has methods on the monitor that can be called, though this should be used cautiously Monitor functionality is implemented in the synchronized keyword, and calling monitor methods directly may produce different results when synchronizing the object 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 201L 5/19

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 201L 6/19

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 static method or block of code on that class is blocked until the lock is released USC CSCI 201L 7/19

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 } 15 16 public class MainClass { 17 public static void main(string [] args) { 18 SyncClass sc = new SyncClass(); 19 // multiple threads created 20 } 21 } 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? Not until T1 releases the lock on sc USC CSCI 201L 8/19

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 } 15 16 public class MainClass { 17 public static void main(string [] args) { 18 SyncClass sc = new SyncClass(); 19 // multiple threads created 20 } 21 } 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? Not until T1 releases the lock on sc USC CSCI 201L 9/19

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 } 15 16 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 } 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? Yes, since T1 acquires the lock on sc and T2 acquires the lock on sc2 USC CSCI 201L 10/19

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 } 15 16 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 } 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? Not until T1 releases the lock on SyncClass USC CSCI 201L 11/19

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 } 15 16 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 } 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? Not until T1 releases the lock on SyncClass USC CSCI 201L 12/19

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 } 15 16 public class MainClass { 17 public static void main(string [] args) { 18 SyncClass sc = new SyncClass(); 19 // multiple threads created 20 } 21 } Thread T1 calls SyncClass.foo(); and gets switched out of the CPU after line 3 Thread T2 calls sc.bar(); Will T2 be able to execute? Yes, since T1 has the lock on SyncClass And T2 has the lock on sc USC CSCI 201L 13/19

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

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) or on a class synchronized(obj) { synchronized(string.class) { // synchronized code // synchronized code } } The lock would have to be obtained on the object obj or the class 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 201L 15/19

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 } 10 11 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 } 21 22 System.out.println("Balance = " + piggy.getbalance()); 23 } 24 } 25 26 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 } 4 Executions USC CSCI 201L 16/19

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 } 10 11 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 } 21 22 System.out.println("Balance = " + piggy.getbalance()); 23 } 24 } 25 26 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 } 4 Executions USC CSCI 201L 17/19

Outline Monitors Program USC CSCI 201L

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? Program USC CSCI 201L 19/19