Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Size: px
Start display at page:

Download "Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico."

Transcription

1 Java Monitors Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 19, 2010 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

2 Outline Mutual Exclusion Monitors vs Semaphores Java Monitors Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

3 SMP Programming Errors Shared Memory parallel programming: saves the programmer from having to map data onto multiple processors. opens up a range of new errors coming from unanticipated shared resource conflicts Race Conditions The output of a program depends on the timing of the threads in the team. Deadlock Threads lock up on a locked resource that will never become free. Livelock Threads working on individual tasks which the ensemble cannot finish. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

4 Race Conditions Insert a node into a doubly-linked list newnode->prev = node; newnode->next = node->next; node->next->prev = newnode; node->next = newnode; Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

5 Race Conditions Insert a node into a doubly-linked list newnode->prev = node; newnode->next = node->next; node->next->prev = newnode; node->next = newnode; Simple counter increment counter++; Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

6 Critical Regions Critical Region Sections of the code that access a shared resource which must not be accessed concurrently by another thread. non-critical entry region critical-region leave region non-critical Unfortunate notation: the critical region is really in data but the guards are in code Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

7 Mutual Exclusion Mutex: mechanism that performs the check that a critical region is free. A mutex has two states, that are usually referred to as unlocked and locked: an unlocked mutex indicates that the critical region is empty a locked mutex indicates that there is some thread inside the critical region All threads must check the state of the mutex before entering the critical region! Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

8 Mutual Exclusion in OpenMP int cnt = 0; #pragma omp parallel { #pragma omp for for(i = 0; i < 20; i++) { if(b[i] == 0) { #pragma omp critical (cnt zeros) { cnt++; /* endif */ a[i] = b[i] * (i+1); /* end for */ /*omp end parallel */ Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

9 Mutex Implementation Simple implementation of mutex using semaphores: Wait(S) (ie, Lock) if (S > 0) then S = S - 1 else suspend execution of this thread Signal(S) (ie, Unlock) if there are processes suspended on this semaphore then wake one of them else S = S + 1 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

10 Monitors Semaphores are low-level synchronization primitives, inherently unstructured usage of the semaphore must be correct for all regions of the program Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

11 Monitors Semaphores are low-level synchronization primitives, inherently unstructured usage of the semaphore must be correct for all regions of the program Monitors provide a structured concurrent programming primitive that concentrates the responsibility of correctness to a few modules. Monitors encapsulate: items of data procedures that operate on this set of data In object-oriented programming, monitors synchronize calls to the methods of a class. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

12 Monitor Concept Already in the 1970s concurrent programmers were faced with the following problems: Concurrent programs were unreliable and hard to write Semaphores were already understood but semaphores were often used incorrectly and a compiler could provide no help on using them Brinch-Hansen and Hoare proposed monitors, which: provide the facility for synchronizing concurrent programs that would be easy to use and could also be checked by a compiler when threads (process) have to access the same variables, they must be granted mutually exclusive access one thread must be able to wait for a condition that another thread can cause without creating a deadlock situation Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

13 Monitors Monitor A monitor is essentially a shared class with explicit queues. A monitor region is code that needs to be executed as one indivisible operation with respect to a particular monitor. A monitor enforces this one-thread-at-a-time execution of its monitor regions. The only way a thread can enter a monitor is by arriving at the beginning of one of the monitor regions associated with that monitor. The only way a thread can move forward and execute the monitor region is by acquiring the monitor. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

14 Monitors When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

15 Monitors When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. When the thread finishes executing the monitor region, it exits and releases the monitor. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

16 Monitors When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. When the thread finishes executing the monitor region, it exits and releases the monitor. A thread can suspend itself inside the monitor by executing a wait command. When a thread executes a wait, it releases the monitor and enters a wait set. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

17 Monitors When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. When the thread finishes executing the monitor region, it exits and releases the monitor. A thread can suspend itself inside the monitor by executing a wait command. When a thread executes a wait, it releases the monitor and enters a wait set. The thread will stay suspended in the wait set until some time after another thread executes a notify command inside the monitor. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

18 Monitors When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. When the thread finishes executing the monitor region, it exits and releases the monitor. A thread can suspend itself inside the monitor by executing a wait command. When a thread executes a wait, it releases the monitor and enters a wait set. The thread will stay suspended in the wait set until some time after another thread executes a notify command inside the monitor. When a thread executes a notify, it continues to own the monitor until it releases the monitor of its own accord, either by executing a wait or by completing the monitor region. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

19 Simple Monitor Operation Entry Set The Owner Wait Set enter acquire release acquire release and exit Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

20 Simple Monitor Operation Entry Set The Owner Wait Set enter acquire release acquire release and exit Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

21 Simple Monitor Operation Entry Set The Owner Wait Set enter acquire release acquire release and exit Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

22 Simple Monitor Operation Entry Set The Owner Wait Set enter acquire release acquire release and exit Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

23 Simple Monitor Operation Entry Set The Owner Wait Set enter acquire release acquire release and exit Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

24 Simple Monitor Operation Entry Set The Owner Wait Set enter acquire release acquire release and exit Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

25 Simple Monitor Operation Entry Set The Owner Wait Set enter acquire release acquire release and exit Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

26 Three Types of Monitors Brinch-Hansen and Hoare Signal and continue Java monitor graphics by Theodore Norvell Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

27 Design Goals of Java Simple programmed without extensive programmer training Object oriented libraries of tested objects that provide functionality ranging from basic data types through I/O and network interfaces to graphical user interface toolkits. Familiar look and feel of C++ without the unnecessary complexities of C++ programmers can easily migrate from C++ Multithreaded library provides the Thread class the run-time system provides monitor and condition lock primitives high-level system libraries have been written to be thread safe Dynamic classes are linked only as needed code modules can be linked in on demand Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

28 Design Goals of Java Architectural neutral and portable generation of bytecodes programs are the same on every platform High Performance interpreter can run at full speed without needing to check the run-time environment automatic garbage collector runs as a low-priority background thread Robust extensive compile-time checking memory management model is extremely simple no pointer arithmetic automatic garbage collection Secure security features designed into the language and run-time system Distributed portable across multiple machine architectures, operating systems, and graphical user interfaces, secure, and high performance Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

29 Simple Example public class Point { protected int x_coord; protected int y_coord; public Point () { place(0, 0); public Point (int x, int y) { place(x, y); public int getx () { return x_coord; public int gety () { return y_coord; public void place (int x, int y) { x_coord = x; y_coord = y; public void move (int x, int y) { x_coord += x; y_coord += y; Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

30 Simple Example public class Point { protected int x_coord; protected int y_coord; public Point () { place(0, 0); public Point (int x, int y) { place(x, y); public int getx () { return x_coord; public int gety () { return y_coord; public void place (int x, int y) { x_coord = x; y_coord = y; public void move (int x, int y) { x_coord += x; y_coord += y; public class Circle extends Point { protected int radius; public Circle() { setradius(0); public Circle(int x, int y, int r) { super(x, y); radius = r; public int getradius () { return radius; public int setradius (int r) { radius = r; public int enlarge (int r) { radius *= r; public float area () { return Math.PI * radius * radius; Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

31 Threads in Java Threads in Java are integrated into the language. class dummythread extends Thread { int id; public dummythread(int id) {this.id = id; public void run(){ System.out.println("Hello World from thread "+id); dummythread dt = new dummythread(42); dt.start(); dt.join(); Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

32 Threads in Java Local variables Every thread has its own set of local variables stored in a stack frame, to which no other thread has access. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

33 Threads in Java Local variables Every thread has its own set of local variables stored in a stack frame, to which no other thread has access. wait, notify and sleep used for inter-thread communication: Thread.wait, goes to sleep until some other thread wakes it up. Thread.notify, wakes up some other thread. Thread.sleep, goes to sleep for some specified number of milliseconds, unless some other thread wakes it up first. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

34 Threads in Java Local variables Every thread has its own set of local variables stored in a stack frame, to which no other thread has access. wait, notify and sleep used for inter-thread communication: Thread.wait, goes to sleep until some other thread wakes it up. Thread.notify, wakes up some other thread. Thread.sleep, goes to sleep for some specified number of milliseconds, unless some other thread wakes it up first. interrupt One thread can interrupt another with Thread.interrupt. The most common use is to wake up a sleeping thread prematurely, or to abort a long I/O. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

35 Mutex in Java Mutual exclusion is straightforward in Java: attribute synchronized. synchronized doit() { /* critical section */ The synchronized attribute ensures that a single thread will be executing method doit() at any time. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

36 Example: Producer-Consumer Problem Construct a FIFO from a finite length buffer: only two operations: append and remove append and remove exclude each other a producer should suspend on a full buffer a consumer should suspend on an empty buffer Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

37 Producer-Consumer with Semaphores void producer() { int item; while (TRUE) { item = produce_item(); /* claim empty spot */ sem_wait(&not_full); sem_wait(&mutex); /* insert, protected by mutex */ insert_item(item); sem_post(&mutex); /* signal filled-in spot */ sem_post(&not_empty); void consumer() { int item; while (TRUE) { /* claim spot in buffer */ sem_wait(&not_empty); sem_wait(&mutex); /* remove, protected by mutex */ item = remove_item(); sem_post(&mutex); /* signal empty spot */ sem_post(&not_full); consume_item(item); Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

38 Producer-Consumer with Java Monitors class Buffer { private Object[] buf; private int in = 0; //index for put private int out = 0; //index for get private int count = 0; //no of items private int size; Buffer(int size) { this.size = size; buf = new Object[size]; synchronized public void put(object o) {... synchronized public Object get() {... Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

39 Producer-Consumer with Java Monitors synchronized public void put(object o) { while (count >= size) { try { wait(); catch(interruptedexception e){ buf[in] = o; ++count; in = (in + 1) % size; notifyall(); synchronized public Object get() { while (count == 0) { try { wait(); catch (InterruptedException e){ Object o = buf[out]; buf[out] = null; // display purposes --count; out = (out + 1) % size; notifyall(); // [count < size] return (o); Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

40 Producer-Consumer with Java Monitors Solution is more structured than semaphores: data and procedures are encapsulated in a single module mutual exclusion is provided automatically by the implementation producer and consumer processes see only abstract put and get Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

41 Limitations of Previous Approach only one queue for threads waiting at an object must always wake up all of the waiting threads Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

42 Limitations of Previous Approach only one queue for threads waiting at an object must always wake up all of the waiting threads the thread awakened by notify() or notifyall() does not get immediate control of the lock. By the time the thread runs, the condition may no longer be true, so it must check the condition again. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

43 Classes Lock and Condition Class Lock provides exclusive access to a shared resource by multiple threads may support multiple associated Condition objects more flexible structuring and more extensive locking operations than using synchronized statement Class Condition factors out the Object monitor methods (wait, notify and notifyall) into distinct objects provides a means for one thread to suspend execution until notified by another thread that some state condition may now be true is intrinsically bound to a lock Where a Lock replaces the use of synchronized methods and statements, a Condition replaces the use of the Object monitor methods. Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

44 Solution using Class Conditions class Buffer { private final ReentrantLock lock = new ReentrantLock(); Condition notempty = new Condition(); Condition notfull = new Condition(); private Object[] buf; private int in = 0; //index for put private int out = 0; //index for get private int count = 0; //no of items private int size; Buffer(int size) { this.size = size; buf = new Object[size]; public void put(object o) {... public Object get() {... Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

45 Solution using Class Monitor public void put(object o) throws InterruptedException { lock.lock(); if (count >= size) notfull.await(); buf[in] = o; ++count; in = (in + 1) % size; notempty.signal(); lock.unlock(); public Object get() throws InterruptedException { lock.lock(); if (count == 0) notempty.await(); Object o = buf[out]; buf[out] = null; // display purposes --count; out = (out + 1) % size; notfull.signal(); lock.unlock(); return (o); Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

46 Review Mutual Exclusion Monitors vs Semaphores Java Monitors Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

47 Next Class Foster s design methodology partitioning communication agglomeration mapping Application Examples Boundary value problem Finding the maximum n-body problem Monteiro, Costa (DEI / IST) Parallel and Distributed Computing / 1

Monitors; Software Transactional Memory

Monitors; Software Transactional Memory Monitors; Software Transactional Memory Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico March 17, 2016 CPD (DEI / IST) Parallel and Distributed

More information

Monitors; Software Transactional Memory

Monitors; Software Transactional Memory Monitors; Software Transactional Memory Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 18, 2012 CPD (DEI / IST) Parallel and

More information

Lecture 10: Introduction to Semaphores

Lecture 10: Introduction to Semaphores COMP 150-CCP Concurrent Programming Lecture 10: Introduction to Semaphores Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 19, 2008 Semaphores Semaphores (Dijkstra 1968) are widely

More information

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data Lecture 4 Monitors Summary Semaphores Good news Simple, efficient, expressive Passing the Baton any await statement Bad news Low level, unstructured omit a V: deadlock omit a P: failure of mutex Synchronisation

More information

Concurrency: a crash course

Concurrency: a crash course Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Concurrency: a crash course Concurrent computing Applications designed as a collection of computational units that may execute

More information

Synchronization. CSCI 5103 Operating Systems. Semaphore Usage. Bounded-Buffer Problem With Semaphores. Monitors Other Approaches

Synchronization. CSCI 5103 Operating Systems. Semaphore Usage. Bounded-Buffer Problem With Semaphores. Monitors Other Approaches Synchronization CSCI 5103 Operating Systems Monitors Other Approaches Instructor: Abhishek Chandra 2 3 Semaphore Usage wait(s) Critical section signal(s) Each process must call wait and signal in correct

More information

Concurrency in Java Prof. Stephen A. Edwards

Concurrency in Java Prof. Stephen A. Edwards Concurrency in Java Prof. Stephen A. Edwards The Java Language Developed by James Gosling et al. at Sun Microsystems in the early 1990s Originally called Oak, first intended application was as an OS for

More information

CSCI 5828: Foundations of Software Engineering

CSCI 5828: Foundations of Software Engineering CSCI 5828: Foundations of Software Engineering Lecture 16: Monitors & Condition Synchronization Slides created by Magee and Kramer for the Concurrency textbook 1 Chapter 5 Monitors & Condition Synchronization

More information

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

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

Concurrent Programming Benoît Garbinato

Concurrent Programming Benoît Garbinato Concurrent Programming Benoît Garbinato 1 Processes & threads A process is a unit of execution managed at the level of the operating system Each process has its own address space, i.e., no other process

More information

What's wrong with Semaphores?

What's wrong with Semaphores? Next: Monitors and Condition Variables What is wrong with semaphores? Monitors What are they? How do we implement monitors? Two types of monitors: Mesa and Hoare Compare semaphore and monitors Lecture

More information

Monitors & Condition Synchronization

Monitors & Condition Synchronization Chapter 5 Monitors & Condition Synchronization monitors & condition synchronization Concepts: monitors: encapsulated data + access procedures mutual exclusion + condition synchronization single access

More information

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems More Synchronization; Concurrency in Java CS 475, Spring 2018 Concurrent & Distributed Systems Review: Semaphores Synchronization tool that provides more sophisticated ways (than Mutex locks) for process

More information

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

Monitors & Condition Synchronization

Monitors & Condition Synchronization Feb. 15, 2012 Monitors & condition Synchronization Concepts: monitors: encapsulated data + access procedures mutual exclusion + condition synchronization single access procedure active in the monitor Models:

More information

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem?

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem? What is the Race Condition? And what is its solution? Race Condition: Where several processes access and manipulate the same data concurrently and the outcome of the execution depends on the particular

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Learning Outcomes Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Sections 2.3 & 2.4 Textbook 2 Making Single-Threaded Code Multithreaded Conflicts between threads over the use of a global variable 3 Inter- Thread and Process Communication

More information

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07 Informatica 3 Marcello Restelli 9/15/07 10/29/07 Laurea in Ingegneria Informatica Politecnico di Milano Structuring the Computation Control flow can be obtained through control structure at instruction

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11: Semaphores I" Brian Logan School of Computer Science bsl@cs.nott.ac.uk Outline of this lecture" problems with Peterson s algorithm semaphores implementing semaphores

More information

CIS Operating Systems Application of Semaphores. Professor Qiang Zeng Spring 2018

CIS Operating Systems Application of Semaphores. Professor Qiang Zeng Spring 2018 CIS 3207 - Operating Systems Application of Semaphores Professor Qiang Zeng Spring 2018 Big picture of synchronization primitives Busy-waiting Software solutions (Dekker, Bakery, etc.) Hardware-assisted

More information

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois 1 Synchronization primitives Mutex locks Used for exclusive access to a shared resource (critical section) Operations:

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

Models of concurrency & synchronization algorithms

Models of concurrency & synchronization algorithms Models of concurrency & synchronization algorithms Lecture 3 of TDA383/DIT390 (Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2016/2017 Today s menu

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

Threads and Parallelism in Java

Threads and Parallelism in Java Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program

More information

Virtual Machine Design

Virtual Machine Design Virtual Machine Design Lecture 4: Multithreading and Synchronization Antero Taivalsaari September 2003 Session #2026: J2MEPlatform, Connected Limited Device Configuration (CLDC) Lecture Goals Give an overview

More information

Monitors & Condition Synchronization

Monitors & Condition Synchronization Chapter 5 Monitors & Condition Synchronization controller 1 Monitors & Condition Synchronization Concepts: monitors (and controllers): encapsulated data + access procedures + mutual exclusion + condition

More information

Part IV Other Systems: I Java Threads

Part IV Other Systems: I Java Threads Part IV Other Systems: I Java Threads Spring 2019 C is quirky, flawed, and an enormous success. 1 Dennis M. Ritchie Java Threads: 1/6 Java has two ways to create threads: Create a new class derived from

More information

Resource management. Real-Time Systems. Resource management. Resource management

Resource management. Real-Time Systems. Resource management. Resource management Real-Time Systems Specification Implementation Verification Mutual exclusion is a general problem that exists at several levels in a real-time system. Shared resources internal to the the run-time system:

More information

Programming Language Concepts: Lecture 11

Programming Language Concepts: Lecture 11 Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]

More information

CS Operating Systems

CS Operating Systems CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,

More information

CS Operating Systems

CS Operating Systems CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,

More information

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2.

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2. Learning Outcomes Concurrency and Synchronisation Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

More information

Advanced Concepts of Programming

Advanced Concepts of Programming Berne University of Applied Sciences E. Benoist / E. Dubuis January 2005 1 Multithreading in Java Java provides the programmer with built-in threading capabilities The programmer can create and manipulate

More information

Dealing with Issues for Interprocess Communication

Dealing with Issues for Interprocess Communication Dealing with Issues for Interprocess Communication Ref Section 2.3 Tanenbaum 7.1 Overview Processes frequently need to communicate with other processes. In a shell pipe the o/p of one process is passed

More information

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

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify http://cs.lth.se/eda040 Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify Klas Nilsson 2016-09-20 http://cs.lth.se/eda040 F4: Monitors: synchronized, wait and

More information

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

Threads. Threads The Thread Model (1) CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5

Threads. Threads The Thread Model (1) CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5 Threads CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5 1 Threads The Thread Model (1) (a) Three processes each with one thread (b) One process with three threads 2 1 The Thread Model (2)

More information

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole Monitors 2 Programming Complexity There are many ways to introduce bugs using locks and semaphores - forget to lock somewhere in the program - forget

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

Lecture 8: September 30

Lecture 8: September 30 CMPSCI 377 Operating Systems Fall 2013 Lecture 8: September 30 Lecturer: Prashant Shenoy Scribe: Armand Halbert 8.1 Semaphores A semaphore is a more generalized form of a lock that can be used to regulate

More information

Reminder from last time

Reminder from last time Concurrent systems Lecture 3: CCR, monitors, and concurrency in practice DrRobert N. M. Watson 1 Reminder from last time Implementing mutual exclusion: hardware support for atomicity and inter-processor

More information

Shared-Memory and Multithread Programming

Shared-Memory and Multithread Programming Shared-Memory and Multithread Programming Pruet Boonma pruet@eng.cmu.ac.th Department of Computer Engineering Faculty of Engineering, Chiang Mai University Based on a material by: Bryan Carpenter Pervasive

More information

Contents. 6-1 Copyright (c) N. Afshartous

Contents. 6-1 Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004

More information

Dr.-Ing. Michael Eichberg

Dr.-Ing. Michael Eichberg Dr.-Ing. Michael Eichberg Concurrent Programming (Overview of the Java concurrency model and its relationship to other models...) (some slides are based on slides by Andy Wellings) 2 Processes vs. Threads

More information

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

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

Monitors & Condition Synchronisation

Monitors & Condition Synchronisation Chapter 5 Monitors & Condition Synchronisation controller 1 Monitors & Condition Synchronisation Concepts: monitors (and controllers): encapsulated data + access procedures + mutual exclusion + condition

More information

Concurrent Programming with OpenMP

Concurrent Programming with OpenMP Concurrent Programming with OpenMP Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 11, 2012 CPD (DEI / IST) Parallel and Distributed

More information

Synchronization COMPSCI 386

Synchronization COMPSCI 386 Synchronization COMPSCI 386 Obvious? // push an item onto the stack while (top == SIZE) ; stack[top++] = item; // pop an item off the stack while (top == 0) ; item = stack[top--]; PRODUCER CONSUMER Suppose

More information

Semaphores. A semaphore is an object that consists of a. methods (e.g., functions): signal and wait. semaphore. method signal. counter.

Semaphores. A semaphore is an object that consists of a. methods (e.g., functions): signal and wait. semaphore. method signal. counter. Semaphores 1 Semaphores A semaphore is an object that consists of a counter, a waiting list of processes, and two methods (e.g., functions): signal and wait. method signal method wait counter waiting list

More information

Synchroniza+on II COMS W4118

Synchroniza+on II COMS W4118 Synchroniza+on II COMS W4118 References: Opera+ng Systems Concepts (9e), Linux Kernel Development, previous W4118s Copyright no2ce: care has been taken to use only those web images deemed by the instructor

More information

Multiple Inheritance. Computer object can be viewed as

Multiple Inheritance. Computer object can be viewed as Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.

More information

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

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018 Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through

More information

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

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions CMSC 433 Programming Language Technologies and Paradigms Fall 2011 Locks & Conditions Intrinsic Lock Example public class RWDictionaryIntrinsicLock { Map m = new TreeMap();

More information

Teaching predicates and invariants on shared data structures in concurrent programming

Teaching predicates and invariants on shared data structures in concurrent programming Teaching predicates and invariants on shared data structures in concurrent programming Stein Gjessing Department of informatics, University of Oslo steing@ifi.uio.no Arne Maus Department of informatics,

More information

Faculty of Computers & Information Computer Science Department

Faculty of Computers & Information Computer Science Department Cairo University Faculty of Computers & Information Computer Science Department Theoretical Part 1. Introduction to Critical Section Problem Critical section is a segment of code, in which the process

More information

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018 SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T 2. 3. 8 A N D 2. 3. 1 0 S P R I N G 2018 INTER-PROCESS COMMUNICATION 1. How a process pass information to another process

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

Introduction to OS Synchronization MOS 2.3

Introduction to OS Synchronization MOS 2.3 Introduction to OS Synchronization MOS 2.3 Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Mahmoud El-Gayyar / Introduction to OS 1 Challenge How can we help processes synchronize with each other? E.g., how

More information

Today: Synchronization. Recap: Synchronization

Today: Synchronization. Recap: Synchronization Today: Synchronization Synchronization Mutual exclusion Critical sections Example: Too Much Milk Locks Synchronization primitives are required to ensure that only one thread executes in a critical section

More information

Real-Time Systems. Lecture #4. Professor Jan Jonsson. Department of Computer Science and Engineering Chalmers University of Technology

Real-Time Systems. Lecture #4. Professor Jan Jonsson. Department of Computer Science and Engineering Chalmers University of Technology Real-Time Systems Lecture #4 Professor Jan Jonsson Department of Computer Science and Engineering Chalmers University of Technology Real-Time Systems Specification Resource management Mutual exclusion

More information

COMP 322: Fundamentals of Parallel Programming

COMP 322: Fundamentals of Parallel Programming COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 30: Advanced locking in Java Vivek Sarkar Department of Computer Science Rice University

More information

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2013 Wait / Notify / NotifyAll Optimistic Retries Composition Follow-up (the risk I mentioned) ReentrantLock, Wait, Notify, NotifyAll Some

More information

C09: Process Synchronization

C09: Process Synchronization CISC 7310X C09: Process Synchronization Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/29/2018 CUNY Brooklyn College 1 Outline Race condition and critical regions The bounded

More information

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

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming. Lecture 07: Advanced Thread programming Software System Components 2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Recap How to deal with race condition in Java Using synchronised

More information

Semaphores and Monitors: High-level Synchronization Constructs

Semaphores and Monitors: High-level Synchronization Constructs 1 Synchronization Constructs Synchronization Coordinating execution of multiple threads that share data structures Semaphores and Monitors High-level Synchronization Constructs A Historical Perspective

More information

MultiJav: A Distributed Shared Memory System Based on Multiple Java Virtual Machines. MultiJav: Introduction

MultiJav: A Distributed Shared Memory System Based on Multiple Java Virtual Machines. MultiJav: Introduction : A Distributed Shared Memory System Based on Multiple Java Virtual Machines X. Chen and V.H. Allan Computer Science Department, Utah State University 1998 : Introduction Built on concurrency supported

More information

CSE 120 Principles of Operating Systems Spring 2016

CSE 120 Principles of Operating Systems Spring 2016 CSE 120 Principles of Operating Systems Spring 2016 Condition Variables and Monitors Monitors A monitor is a programming language construct that controls access to shared data Synchronization code added

More information

Synchronization in Concurrent Programming. Amit Gupta

Synchronization in Concurrent Programming. Amit Gupta Synchronization in Concurrent Programming Amit Gupta Announcements Project 1 grades are out on blackboard. Detailed Grade sheets to be distributed after class. Project 2 grades should be out by next Thursday.

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

Multitasking / Multithreading system Supports multiple tasks

Multitasking / Multithreading system Supports multiple tasks Tasks and Intertask Communication Introduction Multitasking / Multithreading system Supports multiple tasks As we ve noted Important job in multitasking system Exchanging data between tasks Synchronizing

More information

Concurrency: Deadlock and Starvation. Chapter 6

Concurrency: Deadlock and Starvation. Chapter 6 Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other Involve conflicting needs for resources

More information

COMP346 Winter Tutorial 4 Synchronization Semaphores

COMP346 Winter Tutorial 4 Synchronization Semaphores COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated

More information

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set?

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set? Last Class: Synchronization Review Synchronization Mutual exclusion Critical sections Example: Too Much Milk Locks Synchronization primitives are required to ensure that only one thread executes in a critical

More information

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

Synchronization. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University Synchronization Design, Spring 2011 Department of Computer Science Synchronization Basic problem: Threads are concurrently accessing shared variables The access should be controlled for predictable result.

More information

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Operating Systems Lecture 4 - Concurrency and Synchronization Adrien Krähenbühl Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Mutual exclusion Hardware solutions Semaphores IPC: Message passing

More information

The University of Texas at Arlington

The University of Texas at Arlington The University of Texas at Arlington Lecture 6: Threading and Parallel Programming Constraints CSE 5343/4342 Embedded Systems II Based heavily on slides by Dr. Roger Walker More Task Decomposition: Dependence

More information

The University of Texas at Arlington

The University of Texas at Arlington The University of Texas at Arlington Lecture 10: Threading and Parallel Programming Constraints CSE 5343/4342 Embedded d Systems II Objectives: Lab 3: Windows Threads (win32 threading API) Convert serial

More information

Synchronization II. Today. ! Condition Variables! Semaphores! Monitors! and some classical problems Next time. ! Deadlocks

Synchronization II. Today. ! Condition Variables! Semaphores! Monitors! and some classical problems Next time. ! Deadlocks Synchronization II Today Condition Variables Semaphores Monitors and some classical problems Next time Deadlocks Condition variables Many times a thread wants to check whether a condition is true before

More information

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

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization

More information

Synchronization 1. Synchronization

Synchronization 1. Synchronization Synchronization 1 Synchronization key concepts critical sections, mutual exclusion, test-and-set, spinlocks, blocking and blocking locks, semaphores, condition variables, deadlocks reading Three Easy Pieces:

More information

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T Operating Systems Operating Systems Summer 2017 Sina Meraji U of T More Special Instructions Swap (or Exchange) instruction Operates on two words atomically Can also be used to solve critical section problem

More information

Critical Section Problem: Example

Critical Section Problem: Example Why?! Examples Semaphores Monitors Synchronization: Recap Reading: Silberschatz, Ch. 6 Critical Section Problem: Example Insertion of an element into a list. new curr 1. void insert(new, curr) { /*1*/

More information

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst Operating Systems CMPSCI 377 Spring 2017 Mark Corner University of Massachusetts Amherst What is a Monitor? Ties data and the synchronization operations together Monitors guarantee mutual exclusion, i.e.,

More information

C340 Concurrency: Semaphores and Monitors. Goals

C340 Concurrency: Semaphores and Monitors. Goals C340 Concurrency: Semaphores and Monitors Wolfgang Emmerich 1 Goals Introduce concepts of Semaphores Monitors Implementation in Java synchronised methods and private attributes single thread active in

More information

Threads and Java Memory Model

Threads and Java Memory Model Threads and Java Memory Model Oleg Šelajev @shelajev oleg@zeroturnaround.com October 6, 2014 Agenda Threads Basic synchronization Java Memory Model Concurrency Concurrency - several computations are executing

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

CS 31: Intro to Systems Misc. Threading. Kevin Webb Swarthmore College December 6, 2018

CS 31: Intro to Systems Misc. Threading. Kevin Webb Swarthmore College December 6, 2018 CS 31: Intro to Systems Misc. Threading Kevin Webb Swarthmore College December 6, 2018 Classic thread patterns Agenda Pthreads primitives and examples of other forms of synchronization: Condition variables

More information

CSE 153 Design of Operating Systems

CSE 153 Design of Operating Systems CSE 153 Design of Operating Systems Winter 2018 Lecture 10: Monitors Monitors A monitor is a programming language construct that controls access to shared data Synchronization code added by compiler, enforced

More information

7.1 Processes and Threads

7.1 Processes and Threads Chapter 7 Thread Programming 7.1 Processes and Threads Processes are fundamental in any computing system. A process is a program in execution, plus the data, the stack, registers, and all the resources

More information

Producer/Consumer CSCI 201 Principles of Software Development

Producer/Consumer CSCI 201 Principles of Software Development Producer/Consumer CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Producer/Consumer Program USC CSCI 201L Producer/Consumer Overview The producer/consumer

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, Thread. Dongkun Shin, SKKU Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point

More information