Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
1 Race Conditions When threads share access to a common object/data, they can conflict with each other and mess up the consistency of the object/data.
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Multithreading. RHS – SWC 2 What is a thread Inside a single process, multiple threads can be executing concurrently A thread is the execution of (part.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Threads Daniel Bennett, Jeffrey Dovalovsky, Dominic Gates.
1Quiz Modify HelloWorld2.java; –Remove (or comment out) the following 4 lines: Thread thread1 = new Thread(runnable1); Thread thread2 = new Thread(runnable2);
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Multithreading. 2 Threads Program units that execute independently; multiple threads run “simultaneously” Virtual machine executes each thread for short.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
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.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
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.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
Java Programming: Advanced Topics
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.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
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.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
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.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
CS 151: Object-Oriented Design November 21 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Java Thread and Memory Model
Java the UML Way version Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
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.
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.
CS 152: Programming Language Paradigms April 30 Class Meeting Department of Computer Science San Jose State University Spring 2014 Instructor: Ron Mak.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Multithreading. DCS – SWC 2 What is a thread Inside a single process, multiple threads can be executing concurrently A thread is the execution of (part.
Lec 10 agenda >git fetch origin lab10g; > git checkout -b lab10g origin/lab10g; Format/rules for Week 11 Advanced Topics (all beyond the scope of this.
Distributed and Parallel Processing George Wells.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Threads in Java Two ways to start a thread
Multithreading / Concurrency
CSE 501N Fall ‘09 21: Introduction to Multithreading
Multithreaded Programming in Java
Multithreading Chapter 9.
More About Threads.
Threads Chate Patanothai.
ITEC324 Principle of CS III
Multithreading Chapter 23.
Multithreading.
Java Based Techhnology
Multithreading.
Java Concurrency.
Java Concurrency.
Threads and Multithreading
Chapter 9 Multithreading
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee

 Thread Basics  Thread Synchronization

 Thread: program unit that is executed independently  Multiple Threads: Program units what can be executed in parallel.  Multiple threads run simultaneously.  When executes ▪ Multiprocessor computers: threads actually run in parallel OR ▪ Illusion of threads running in parallel. ▪ That is, Virtual machine executes each thread for short time slice. Thread scheduler activates, deactivates threads.

 How to implement Running Threads  Define class that implements Runnable interface. Runnable has one method. void run()  Place thread action into run() method  Construct an object of the class which implements the Runnable Interface  Construct an object of Thread class  start() thread

public class MyRunnable implements Runnable { public void run() { thread action }... Runnable r = new MyRunnable(); Thread t = new Thread(r); t.start();

 Run two threads in parallel  Each thread  prints 10 greetings for (int i = 1; i <= 10; i++) { System.out.println(i + ": " + greeting); Thread.sleep(100); }  After each printout, sleep for 100 milliseconds  All threads should occasionally yield control  sleep() throws InterruptedException

 Ch9/greeting/GreetingProducer.java Ch9/greeting/GreetingProducer.java  Ch9/greeting/ThreadTester.java Ch9/greeting/ThreadTester.java

 Sample Output (Note: output not exactly interleaved.) 1: Hello, World! 1: Goodbye, World! 2: Hello, World! 2: Goodbye, World! 3: Hello, World! 3: Goodbye, World! 4: Hello, World! 4: Goodbye, World! 5: Hello, World! 5: Goodbye, World! 6: Hello, World! 6: Goodbye, World! 7: Hello, World! 7: Goodbye, World! 8: Goodbye, World! 8: Hello, World! 9: Goodbye, World! 9: Hello, World! 10: Goodbye, World! 10: Hello, World! ☞ The thread scheduler gives no guarantee about the order in which threads are executed. Moreover, there will always be slight variations in running times, especially when calling operating system services (such as input and output). Thus, you should expect that the order in which each thread gains control appears to be somewhat random.

 Each thread has  thread state  priority  Thread states:  new ▪ before start() called  runnable  blocked  dead ▪ after run() method exits

 Reasons for entering the blocked state:  Sleeping  Waiting for I/O  Waiting to acquire lock (later)  Waiting for condition (later)  Unblocks only if the reason for the blocking goes away

 Scheduler activates a new (next) thread if  a thread has completed its time slice  a thread has blocked itself  a thread with higher priority has become runnable  Scheduler determines a new thread to run by  looking only at all runnable threads, and  picking one with the highest priority value. (The priority values are system-dependant and not adjustable by an application programmer.) OR  Picking one at random or using a round-robin scheme to gives each thread a chance.

 Normal way to terminate a thread  Thread terminates when run() exits  However, you sometimes need to terminate running thread  (Ex) you may have several threads attempting to find a solution to a problem. As soon as the first one has succeeded, you can terminate the other ones.

 Interrupt thread by calling interrupt()  Don't use deprecated stop() method ▪ It is deprecated since the method can hold a shared resource and does not release it.  Calling t.interrupt() doesn't actually interrupt t ; just sets a “ interrupted ” flag  The run() method should check whether its thread has been interrupted. In that case, it should do any necessary cleanup and exit. The most practical strategy for dealing with thread interruptions is to surround the entire work portion of the run() method with a try{ } block that catches the InterruptedException.

public class MyRunnable implements Runnable { public void run() { try { while (...) { do work Thread.sleep(...); } } catch (InterruptedException e) {} clean up }

 More robust way: sleep() and wait() occasionally, catch an exception and react to interruption  sleep() and wait() check the “ interrupted ” flag and, if the flag is set, the methods throw InterruptedException and then the interruption status is cleared!  Occasionally, when it is inconvenient to call sleep() or wait(), you should check the “ interrupted ” flag manually Thread.currentThread().isInterrupted()  Recommendation: Terminate run() when sensing interruption

public class MyRunnable implements Runnable { public void run() { try { while (...) { do work Thread.sleep(...); } } catch (InterruptedException e) {} clean up }

 Example  Two producers, one consumer  Each producer thread inserts 100 greetings into the same queue.  Each consumer thread removes all of the greetings in the queue.

 In the try{ } block int i = 1; while (i <= greetingCount) { if (!queue.isFull()) { queue.add(i + ": " + greeting); i++; } Thread.sleep((int)(Math.random() * DELAY)); }

 In the try{ } block int i = 1; while (i <= greetingCount) { if (!queue.isEmpty()) { Object greeting = queue.remove(); System.out.println(greeting); i++; } Thread.sleep((int)(Math.random() * DELAY)); }

1: Hello, World! 1: Goodbye, World! 2: Hello, World! 3: Hello, World!... 99: Goodbye, World! 100: Goodbye, World!

 Sometimes, the program will corrupt the queue and not work correctly.  The consumer thread gets stuck and won ’ t complete. Even though 200 greetings were inserted in the queue, it can ’ t retrieve them all.  It may complete, but print the same greetings repeatedly.  Can you spot the problem?  Can see problem better when turning debugging on queue.setDebug(true);  Ch9/queue1/ThreadTester.java Ch9/queue1/ThreadTester.java  Ch9/queue1/Producer.java Ch9/queue1/Producer.java  Ch9/queue1/Consumer.java Ch9/queue1/Consumer.java  Ch9/queue1/BoundedQueue.java Ch9/queue1/BoundedQueue.java

 Race Condition occurs if the effect of multiple threads on shared data depends on the order in which the threads are scheduled.  Multiple threads, in their race to complete their respective task, rush to win the race.

 Race Condition Scenario  First thread calls add and executes elements[tail] = anObject;  First thread at end of time slice  Second thread calls add and executes elements[tail] = anObject; tail++;  Second thread at end of time slice  First thread executes tail++;

 To fix the race conditions, you need to ensure that only one thread manipulates the queue at any given moment.

 Locking Mechanism  Thread can temporarily acquire ownership of a lock  When another thread tries to acquire same lock, it is blocked.  When first thread releases the lock, other threads are unblocked and try again  Two kinds of locks  Objects of ReentrantLock class or another class implementing java.util.concurrent.Lock interface type in java.util.concurrent.locks packageLocks  Locks that are built into every Java object

aLock = new ReentrantLock();... aLock.lock(); try { protected code } finally { aLock.unlock(); } ☞ The finally clause ensures that the lock is unlocked even when an exception is thrown in the protected code.

1. First thread calls add and acquires lock, then executes elements[tail] = anObject; 2. Second thread calls add and tries to acquire lock, but it is blocked 3. First thread executes tail++; 4. First thread completes add, releases lock 5. Second thread unblocked 6. Second thread acquires lock, starts executing protected code ☞ The remove() method of the queue must be protected by the same lock. After all, if one thread calls add(), we don ’ t want another thread to execute the remove() method on the same object.

 A deadlock occurs if no thread can proceed because each thread is waiting for another to do some work first.  (Ex) Having a lock is still not enough to synchronize add() and remove() methods. Consider the following code. It can still be interrupted. What if the thread is interrupted right after isFull() is called in the if condition? if (!queue.isFull()) queue.add(...);

 Thus, the test using the if statement must move test inside add method public void add(E newValue) { queueLock.lock(); try { while (queue is full) wait for more space... } finally { qeueLock.unlock(); } }

 Problem  How can you wait for more space? You can ’ t simply call sleep() inside the try block. If a thread sleeps after locking queueLock, no other thread can remove elements because that block of code is protected by the same lock. The consumer thread will call remove, but it will simply be blocked until the add() method exits. But, the add method doesn ’ t exit until it has space available. This is called a deadlock.  Deadlock vs. Live lock

 Use an object of a class which implements the Condition interface to manage "space available" condition private Lock queueLock = new ReentrantLock(); private Condition spaceAvailableCondition = queueLock.newCondition();  Calling await() on a Condition object makes the current thread wait and allows another thread to acquire the lock. public void add(E newValue) {... while (size == elements.length) spaceAvailableCondition.await();... }

 signalAll() or signal(): The signalAll() method unblocks all threads waiting for the condition, making them all runnable again. It is called whenever the state of an object has changed in a way that might benefit waiting threads. public E remove() {... E r = elements[head];... spaceAvailableCondition.signalAll(); // Unblock waiting threads return r; }  Ch9/queue2/BoundedQueue.java Ch9/queue2/BoundedQueue.java

 Every java object has an associated object lock.  To acquire and release the lock belonging to the implicit parameter of a method: simply tag the method with the synchronized keyword.  To protect an queue object public class BoundedQueue { public synchronized void add(E newValue) {... } public synchronized E remove() {... }... }

 Each object lock comes with one condition object.  To wait on that condition, call wait()  Object.wait() blocks current thread and adds it to wait set  To signal that the condition has changed, call notifyAll() or notify()  Object.notifyAll unblocks waiting threads public synchronized void add(E newValue) throws InterruptedException { while (size == elements.length) wait(); elements[tail] = anObject;... notifyAll(); // notifies threads waiting to remove elements }  Ch9/queue3/BoundedQueue.java Ch9/queue3/BoundedQueue.java

 Object = phone booth  Thread = person  Locked object = closed booth  Blocked thread = person waiting for booth to open