Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency (p2) synchronized (this) { doLecture(part2); } synchronized (this) { doLecture(part2); }
Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Practice Session 7 Synchronization Liveness Guarded Methods Model
System Programming Practical Session 5 Liveness, Guarded Methods, and Thread Timing.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
26-Jun-15 Threads and Turns. Thread review There are two ways to create a Thread object.. Extend Thread and supply a run method: class MyThread extends.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
ThreadThread Thread Basics Thread Synchronization Animations.
1 Thread Pools. 2 What’s A Thread Pool? A programming technique which we will use. A collection of threads that are created once (e.g. when server starts).
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Week 9 Building blocks.
Threads some important concepts Simon Lynch
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
1 (Worker Queues) cs What is a Thread Pool? A collection of threads that are created once (e.g. when a server starts) That is, no need to create.
Java Threads 1 1 Threading and Concurrent Programming in Java Queues D.W. Denbo.
Threading Eriq Muhammad Adams J
Practice Session 9 Exchanger CyclicBarrier Exceptions.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Synchronizing threads, thread pools, etc.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Multithreading [Modified]
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Lecture 6: Monitors & Semaphores. Monitor Contains data and procedures needed to allocate shared resources Accessible only within the monitor No way for.
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.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
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.
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.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
Multithreading / Concurrency
Thread Pools (Worker Queues) cs
Multi Threading.
Thread Pools (Worker Queues) cs
Practice Session 8 Lockfree LinkedList Blocking queues
Multithreading Chapter 9.
System Programming Practical Session 7
Threads Chate Patanothai.
Condition Variables and Producer/Consumer
Cancellation.
Condition Variables and Producer/Consumer
Software Engineering and Architecture
some important concepts
More concurrency issues
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread cancellation: Stop shouldStop Interrupt

Blocking Queues An ordinary queue with a special feature. The queue behaves differently in two cases: – Empty queue case Thread wants to pop head element of the queue. Thread is blocked until the queue stops being empty – Full queue case Thread wants to add an element to the queue. Thread is blocked until the queue stops being full

Java Blocking Queue API: – Package java.util.concurrent – Interface: BlockingQueue “Our” Implementation: – class MyBlockingQueue implements BlockingQueue Java’s Implementation: – Java.util.concurrent.ArrayBlockingQueue Functions: – void put(E o) Adds the specified element to this queue, waiting if necessary for space to become available. – E take() Retrieves and removes the head of this queue, waiting if no elements are present on this queue. API Website: – –

MyBlockingQueue Private Fields: private ArrayList fList; The queue object. Not synchronized. private final int fMax; Our queue’s maximum size. Received upon construction. Fixed Size. Constructor: MyBlockingQueue(int max){ fList = new ArrayList(); fMax = max; } Private Functions: private synchronized int getSize(){ return fList.size(); }

My Blocking Queue – put() public synchronized void put (E obj){ while(getSize()>=fMax){ try{ this.wait(); } catch (InterruptedException ignored){} } fList.add(obj); // wakeup everybody. If someone is waiting in the get() // method, it can now perform the get. this.notifyAll(); }

MyBlockingQueue – take() public synchronized E take (){ while(size()==0){ try{ this.wait(); } catch (InterruptedException ignored){} } E obj = fList.get(0); fList.remove(0); // wakeup everybody. If someone is waiting in the add() // method, it can now perform the add. this.notifyAll(); return obj; }

The Producer-Consumer Problem A classical multi-process (thread) synchronization problem. Uses a bounded (fixed-size) queue. Two major groups: – Producer(s): A Thread that generates new objects Adds them to shared space – Consumer(s): A Thread that removes objects from shared space. Uses them. Full queue: – A producer thread is blocked, until a free space is available. Empty queue: – A consumer thread is blocked, until the queue receives new object.

Producer-Consumer Implementation Using ArrayBlockingQueue Three Classes: – Producer implements Runnable – Consumer implements Runnable – Driver class (includes main function) Code Example: – Producer-Consumer The output of the program does not necessarily reflect its flow, since printing and accessing the queue are 2 separate operations (the operating system might decide to run the first command, and then stops the thread and runs another thread, before this thread performs the second command). Surrounding the 2 commands with a synchronized block solves this problem, but it’s not advisable since it blocks too much.

java.util.concurrent.Semaphore A data structure used to restrict access to shared resources. A synchronized block allows access for one thread at a time. A semaphore gives N>=1 permits to threads, at the same time, over a resource/the code that comes after semaphore.acquire( ). If the program uses acquire(), without a number, then the semaphore gives access to N threads. API: – tml

Semaphore construction: – Semaphore sem = new Semaphore(int permits): permits holds the maximal number of possible threads to access an object at the same time. Fairness is false in this case, permits are given in an arbitrary order. – Semaphore sem = new Semaphore(int permits, boolean fair) Fairness is true, gives permits to threads in FIFO manner. First thread requesting access, is given access. Downside: – It takes more time for the virtual machine to order the acquisition of the permits than to allow an arbitrary thread to acquire a permit.

sem.release(): releases a permit returning it to the semaphore. sem.release(n): releases n permits - adds n permits to the semaphore (n can be larger than the value we used at initialization). sem.reducePermits(n): shrinks the number of available permits by the indicated reduction; does not block like acquire(). (protected method) sem.acquire(): acquire a permit sem.acquire(n ): acquire n permits More methods in the api: Semaphore.html Some Semaphore Methods

Uses Limiting concurrent access to a resource, in general. Limiting the number of created threads. Limiting the number of concurrent connections. Etc.

Code Example – In the Club Groups of people asking for entrance permits to a club. FiftyCentTheBouncer Club 5 entrance permits Group1 requests n1 entrance permits Group2 requests n2 entrance permits Group3 requests n3 entrance permits Group4 requests n4 entrance permits Group5 requests n5 entrance permits

Callable java.util.concurrent.Callable : Like Runnable, but: – Allows Threads to return values. – Allows Threads to throw exceptions. – Uses generics to define object types. – Class Header: public class implements Callable – Required Functions: public call() Same purpose as Runnable’s run()

Futures Used in combination with the Executor. An object that represents the result of a Callable. Can retrieve the Callable’s result: – Using get() method – The result can be retrieved only when the computation has completed. – get() blocks, until value can be retrieved. Allows cancellation of Thread execution. – Using cancel() method – Cannot cancel a completed Callable. Interface:

Code Example – The Price is Right A game were contestants try to guess the price of an item, given a max and a min value. The contestant whose guess is closest to the actual price wins. ThePriceIsRight Item: Xerox Phaser 5500DN Workgroup Laser Printer. Actual price: $500 Contestant1 makes a guess between $1 - $1000 Contestant2 makes a guess between $1 - $1000 Contestant3 makes a guess between $1 - $1000 Contestant4 makes a guess between $1 - $1000 Contestant5 makes a guess between $1 - $1000

Create n Callables and save their futures in a collection. While not all n values were retrieved: – Acquire a semaphore (a semaphore is released at the end of each Callable) – Look for the Callable that finished, using the collection of futures. – Get the value returned by the callable that finished. – Set the found future to null in the collection, so it won’t be checked again.

Notes Runnable, Callable are objects, they are not threads. Threads receive these objects and run them. Threads receive a reference to these objects. Threads do not create a new copy of the runnable or the callable objects. Having a stateful runnable/callable object (changes its own values) and running more than one thread to it will cause problems if not synchronized! Runnable objects cannot throw exceptions back to main. Run() method does not throw Exception Callable objects can throw exceptions back to main. Call() method throws Exception.

Thread Cancellation Thread t = new Thread(…); How? – t.stop() method. (deprecated) Good? (doesn’t leave the objects in a stable state) – Unsafe! – Releases all object locks instantly. Then, how? – By implementing a “shouldStop” method. – “shouldStop” checks a flag in the thread. – Case where a flag is true, thread stops working. Good? – Not always! – Thread might not take too long to stop: In case where the thread in sleep condition. – Thread might not stop at all: In case where the thread in wait() condition. And no notify() on the horizon.

shouldStop Example class Worker implements Runnable { private boolean fShouldStop ; public Worker() { fShouldStop=false; } public synchronized void stop() { fShouldStop = true; } public synchronized boolean shouldStop() { return fShouldStop; } public void run() { while (!this.shouldStop()){ doTheWork(); } System.out.println("stopping…"); }

interrupt() The interrupt() mechanism. Each thread stores an internal flag known as interrupt status. Methods: – t.isInterrupted() Checks whether the thread is interrupted or not. – t.interrupt(): If t is blocked (wait(), sleep()) then – InterruptedException is thrown. – Forces the thread to wake up! From sleep or wait mode. Otherwise – isInterrupted() will return true. – Behaves the same as shouldStop. Note: – If InterruptedException is thrown, isInterrupted() will return false unless interrupt() is called again.

interrupt() example class Worker implements Runnable { public Worker() { } public boolean condition() { return false; } public synchronized void doSomeWork() { while (!this.condition() && !Thread.currentThread().isInterrupted()) { try { this.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // re-raise the interrupt. This is very important! break; // get out of the loop (and out of the method) } public void run() { while (!Thread.currentThread().isInterrupted()){ doSomeWork(); } System.out.println("stopping ;)"); }

interrupt() example continued class Driver{ public static void main(String[] args) { Thread t = new Thread(new Worker()); t.start(); try { Thread.sleep(100); } catch (InterruptedException e) { } t.interrupt(); }

Advanced Thread Synchronization Methods

java.util.concurrent.CountDownLatch What? – A synchronization method. – Allows one or more threads to wait until other threads complete. How? – A CountDownLatch object is initialized with a starting value. – The await() method blocks until the current count reaches zero due to invocations of the countDown() method in other threads. – After which all waiting threads are released and any subsequent invocations of await return immediately. Properties: – The CountDownLatch cannot be reset. – This is a good practice for initialization/finalization purposes. – When we need to use some waiting point only once, the latch is best to do the job.

Example: – In multiplayer games you don’t want any player to start until all players have joined. – This procedure works only once at the start of the game. API: – l/concurrent/CountDownLatch.html Code Example: server waiting for clients to finish, before it shuts down. – CountDownLatch