Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
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.
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.
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
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.
Chapter 21 – Multithreading
CS 11 java track: lecture 7 This week: Web tutorial:
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
ThreadThread Thread Basics Thread Synchronization Animations.
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.
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Chapter 21 – Multithreading Big Java Early Objects by Cay Horstmann Copyright © 2014 by John Wiley & Sons. All rights reserved.
Internet Software Development More stuff on Threads Paul Krause.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CSE 219 Computer Science III Multithreaded Issues.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 19 Multithreading.
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.
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
111 © 2002, Cisco Systems, Inc. All rights reserved.
Next week (July 21) –No class –No office hour. Problem Multiple tasks for computer –Draw & display images on screen –Check keyboard & mouse input –Send.
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.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Synchronizing threads, thread pools, etc.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
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.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
1 Chapter 19 Multithreading. 2 Objectives F To understand the concept of multithreading and apply it to develop animation (§19.2). F To develop thread.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
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.
Chapter 3 Implementing Classes
Parallel Thinking with Java Multithreading. Introduction Algorithms which make use of more than one processor Very hot topic today because all chip manufacturers.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
CSCD 330 Network Programming
Multithreading / Concurrency
Multi Threading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Java Concurrency.
Multithreading Chapter 9.
Implementing Classes Yonglei Tao.
Threads and Concurrency in Java: Part 2
Threads Chate Patanothai.
Java Concurrency.
Chapter Three - Implementing Classes
Multithreading.
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading : synchronization

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must be able to lock an object temporarily When a thread has the object locked, no other thread can modify the state of the object. In Java, use synchronized methods to do this Tag all methods that contain thread-sensitive code with the keyword synchronized

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.3 Synchronized Methods public class BankAccount { public synchronized void deposit(double amount) {... } public synchronized void withdraw(double amount) {... }... }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.4 With synchronization, the final balance is always correct!

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.5 Synchronized Methods By declaring both the deposit and withdraw methods to be synchronized  Our program will run correctly  Only one thread at a time can execute either method on a given object  When a thread starts one of the methods, it is guaranteed to execute the method to completion before another thread can execute a synchronized method on the same object.

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.6 By executing a synchronized method:  The thread acquires the object lock.  No other thread can acquire the lock.  No other thread can modify the state of the object until the first thread is finished. Every object in Java has a lock associated with it. Every object can maintain a list of waiting threads.

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.7 Visualization of Synchronized Thread Behavior Imagine the object is a restroom that only one person can use at a time The threads are people If the restroom is empty, a person may enter If a second person finds the restroom locked, the second person must wait until it is empty If multiple people want to gain access to the restroom, they all wait outside The people may not form an orderly queue A randomly chosen person may gain access when the restroom becomes available again

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.8 Deadlock A deadlock occurs if no thread can proceed because each thread is waiting for another to do some work first. In other words, a deadlock occurs when two threads end up waiting for each other to release a lock they need. Since neither one can proceed, neither one can release the lock it holds, and they both stop running. When you are synchronizing threads, you must be careful to avoid deadlock.

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.9 BankAccount example public synchronized void withdraw(double amount) { while (balance < amount) //wait for balance to grow... }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.10 The method can lead to deadlock The thread sleeps to wait for balance to grow, but it still has the lock No other thread can execute the synchronized deposit method If a thread tries to call deposit, it is blocked until the withdraw method exits withdraw method can't exit until it has funds available DEADLOCK occurs!

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.11 Avoiding Deadlock The wait method temporarily releases the object lock and deactivates the thread Restroom analogy  Don't want the person in the restroom to go to sleep if there is no toilet paper.  Think of the person giving up and leaving  This gives another person a chance to enter and refill the toilet paper

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.12 withdraw Method to Avoid Deadlock with wait() public synchronized void withdraw(double amount) throws InterruptedException { while (balance < amount) wait();... }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.13 Wait and NotifyAll A thread that calls wait is in a blocked state It will not be activated by the thread scheduler until it is unblocked It is unblocked when another thread calls notifyAll When a thread calls notifyAll, all threads waiting on the object are unblocked Only the thread that has the lock can call notifyAll

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.14 Restroom wait/notifyAll Analogy The thread calling wait() corresponds to the person who enters the restroom and finds there is no toilet paper The person then leaves the restroom and waits outside Other people may enter and leave, but the first person just waits Eventually an attendant enters the restroom, refills the toilet paper, and shouts a notification All the waiting people compete for the restroom

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.15 File BankAccountThreadTest.java (Modified, Using synchronized methods) /** This program runs four threads that deposit and withdraw money from the same bank account. */ public class BankAccountThreadTest { public static void main(String[] args) {

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.16 BankAccount account = new BankAccount(); DepositThread t0 = new DepositThread(account, 100); WithdrawThread t1 = new WithdrawThread(account, 100); DepositThread t2 = new DepositThread(account, 100); WithdrawThread t3 = new WithdrawThread(account, 100); t0.start(); t1.start(); t2.start(); t3.start(); } //end main } // end class

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.17 File BankAccount.java (modified) /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { /** Constructs a bank account with a zero balance */ public BankAccount() { balance = 0; } /** Deposits money into the bank amount the amount to deposit */

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.18 public synchronized void deposit(double amount) { System.out.print("Depositing " + amount); double newBalance = balance + amount; System.out.println(", new balance is " + newBalance); balance = newBalance; notifyAll(); } /** Withdraws money from the bank amount the amount to withdraw */ public synchronized void withdraw(double amount) throws InterruptedException { while (balance < amount) wait(); System.out.print("Withdrawing " + amount); double newBalance = balance - amount; System.out.println(", new balance is " + newBalance); balance = newBalance; }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.19 /** Gets the current balance of the bank the current balance */ public synchronized double getBalance() { return balance; } private double balance; } // end class

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.20 Be careful! A common error is to have threads call wait without matching calls to notifyAll by other threads. Whenever you call wait, ask yourself which call to notifyAll will notify your thread. The thread that calls notifyAll must own the lock on the object on which notifyAll is called. Otherwise, an IllegalMonitorStateException is thrown.

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.21 notify( ) While notifyAll( ) wakes up all threads that are waiting on the object, notify( ) wakes up only a single thread that is waiting on the object. If any threads are waiting on the object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. It's better to use notifyAll( ).

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.22 Complex Deadlocks Using the wait and notifyAll methods does not solve all deadlocks. The following is an example. We have three accounts: account0, account1, and account2 ; and three transfer threads: t0, t1, and t2. A transfer thread transfers money from two accounts into a third. t0 repeatedly transfers $500 each from account1 and account2 to account0. t1 repeatedly transfers $500 each from account2 and account0 to account1. t2 repeatedly transfers $500 each from account0 and account1 to account2.

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.23 If the three threads take turns and each thread executes one iteration before losing control of the CPU, then the program runs indefinitely: account0account1account2 Initial balance$1000 After t0 iteration$2000$500 After t1 iteration$ After t2 iteration$1000

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.24 But if it happens that t0 executes two iterations before t1 and t2 get a chance, then the program deadlocks: account0account1account2 Initial balance$1000 After t0 iteration$2000$500 After t0 iteration$ Now none of the three threads can progress, and a deadlock occurs.

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.25 Most of the time, the program will carry out the transfers successfully, but once in a while you may be able to observe a deadlock. Programmers who create multithreaded programs must make an effort to prove rigorously why their threads cannot deadlock no matter in which order they are executed. Running a few experiments is not enough. It can be misleading.

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.26 File BankAccountThreadTest.java /** This program uses three threads that transfer money between three accounts. It can occasionally deadlock. */ public class BankAccountThreadTest { public static void main(String[] args) { BankAccount account0 = new BankAccount(1000); BankAccount account1 = new BankAccount(1000); BankAccount account2 = new BankAccount(1000); //... Put your code here... }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.27 File TransferThread.java /** A transfer thread repeatedly transfers money between three bank accounts. */ class TransferThread extends Thread { /** Constructs a transfer account1 the first account to account2 the second account to account3 the account to anAmount the amount to withdraw from each of the first two accounts. */ public TransferThread(BankAccount account1, BankAccount account2, BankAccount account3, double anAmount) { //... Put your code here... }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.28 public void run() { try { for (int i = 1; i <= REPETITIONS && !isInterrupted(); i++) { //... Put your code here... sleep(DELAY); } catch (InterruptedException exception) { } private BankAccount from1, from2, to; private double amount; private static final int REPETITIONS = 10; private static final int DELAY = 10; }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.29 /** A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { /** Constructs a bank account with a given initialBalance the initial balance */ public BankAccount(double initialBalance) { balance = initialBalance; } File BankAccount.java

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.30 /** Deposits money into the bank amount the amount to deposit */ public synchronized void deposit(double amount) { balance = balance + amount; System.out.println(Thread.currentThread().getName() + " Depositing " + amount + ", new balance is " + balance); notifyAll(); }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.31 /** Withdraws money from the bank amount the amount to withdraw */ public synchronized void withdraw(double amount) throws InterruptedException { while (balance < amount) { System.out.println(Thread.currentThread().getName() + " Waiting..."); wait(); } balance = balance - amount; System.out.println(Thread.currentThread().getName() + " Withdrawing " + amount + ", new balance is " + balance); }

Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.32 /** Gets the current balance of the bank the current balance */ public synchronized double getBalance() { return balance; } private double balance; } //end class