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.

Slides:



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

1Deadlock DeadlockedBankAccount –withdraw(){ lock.lock(); while(balance
Multithreading Horstmann ch.9. Multithreading Threads Thread states Thread interruption Race condition Lock Built-in lock java.util.concurrent library.
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:
객체지향프로그래밍강원대학교 1/62 제 13 주 멀티쓰레딩 (Multi-threading) 제 13 주 목표 여러 쓰레드가 어떻게 병렬도 실행되는 지 이해함 쓰레드를 구현하는 법을 배움 레이스 컨디션과 데드락에 대해 배움 락과 컨디션을 사용함으로써 공유자료가 엉망이 되지.
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
CS444/CS544 Operating Systems Synchronization 2/21/2007 Prof. Searleman
Chapter Twenty: Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand.
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.
Multithreading.
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.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
CSE 219 Computer Science III Multithreaded Issues.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race conditions.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
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.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Multi-Threaded Programming Design CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Internet Software Development Controlling Threads Paul J Krause.
1 G53SRP: Java Concurrency Control (1) - synchronisation Chris Greenhalgh School of Computer Science.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
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.
CMSC 330: Organization of Programming Languages Threads.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
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)
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
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.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Programming and Problem Solving With Java Copyright 1999, James M. Slack Threads and Animation Threads Animation.
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.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 19 – Multithreading.
Producer/Consumer CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1/66 자바프로그래밍강원대학교 14 주 멀티쓰레딩 Multithreading. 2/66 Process and Thread 자바프로그래밍강원대학교
Parallel Thinking with Java Multithreading. Introduction Algorithms which make use of more than one processor Very hot topic today because all chip manufacturers.
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.
Chapter 23 Multithreading. Chapter Goals To understand how multiple threads can execute in parallel To learn how to implement threads To understand race.
CSCD 330 Network Programming
Multithreading / Concurrency
Chapter 22 – Multithreading
Multithreading.
CSE 501N Fall ‘09 21: Introduction to Multithreading
Chapter 22 – Multithreading
Threads Chate Patanothai.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Thread Synchronization
Multithreading.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
CSCD 330 Network Programming
Presentation transcript:

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 Reentrant lock can be reacquired by same thread –As many times as desired –No other thread may acquire lock until has been released same number of times has been acquired interface Lock { Void lock(); Void unlock(); …//some other stuff }

Synchronization Using Locks public class Example extends Thread { private static int cnt = 0; private Lock lock; public Example(){ lock = new ReentrantLock(); } public void run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); }... } Creating a lock, for protecting the shared state Acquires the lock; Only succeeds if not held by another thread Releases the lock

An example with bank accounts // A bank account has a balance that can be changed by // deposits and withdrawals. public class BankAccount { public BankAccount() { balance = 0; } public void deposit(double amount) { System.out.print("Depositing " + amount); double newBalance = balance + amount; System.out.println(", new balance is " + newBalance); balance = newBalance; } public void withdraw(double amount) { System.out.print("Withdrawing " + amount); double newBalance = balance - amount; System.out.println(", new balance is " + newBalance); balance = newBalance; } public double getBalance() { return balance; } private double balance; }

/** A deposit runnable makes periodic deposits to a bank account. */ public class DepositRunnable implements Runnable { public DepositRunnable(BankAccount anAccount, double anAmount, int aCount) { account = anAccount; amount = anAmount; count = aCount; } public void run() { try { for (int i = 1; i <= count; i++) { account.deposit(amount); Thread.sleep(DELAY); } catch (InterruptedException exception) {} } private static final int DELAY = 1; private BankAccount account; private double amount; private int count; }

/** A withdraw runnable makes periodic withdrawals from a bank account. */ public class WithdrawRunnable implements Runnable { public WithdrawRunnable(BankAccount anAccount, double anAmount, int aCount) { account = anAccount; amount = anAmount; count = aCount; } public void run() { try { for (int i = 1; i <= count; i++) { account.withdraw(amount); Thread.sleep(DELAY); } catch (InterruptedException exception) {} } private static final int DELAY = 1; private BankAccount account; private double amount; private int count; }

/** This program runs four threads that deposit and withdraw money from the same bank account. */ public class BankAccountThreadTester { public static void main(String[] args) { BankAccount account = new BankAccount(); final double AMOUNT = 100; final int REPETITIONS = 5; DepositRunnable d1 = new DepositRunnable( account, AMOUNT, REPETITIONS); WithdrawRunnable w1 = new WithdrawRunnable( account, AMOUNT, REPETITIONS); DepositRunnable d2 = new DepositRunnable( account, AMOUNT, REPETITIONS); WithdrawRunnable w2 = new WithdrawRunnable(account, AMOUNT, REPETITIONS); Thread t1 = new Thread(d1); Thread t2 = new Thread(w1); Thread t3 = new Thread(d2); Thread t4 = new Thread(w2); t1.start(); t2.start(); t3.start(); t4.start(); }

Using Locks to Synchronize Threads Step 1: add a lock to the class that owns the shared resource Step 2: surround any code that uses the shared resource by a call to lock ( ) and unlock ( ) public class BankAccount { public BankAccount() { balanceChangeLock = new ReentrantLock(); // the rest of your code here } … // more code here private Lock balanceChangeLock; } balanceChageLock.lock ( ); try { // Code that changes the balance } finally { balanceChangeLock.unlock ( ); } Use finally block to ensure that the lock is released even if exception happens

Deadlocks Deadlock occurs when a thread acquires a lock and then must wait for another thread to do some work before proceeding, but where the second thread needs the lock to proceed Example: Let’s assume we want to prevent a withdrawal if there is not enough balance –In a single threaded world, we might code: if (account.getBalance ( ) >= amount) account.withdraw (amount); –For multi-threading: public void withdraw(double amount){ balanceChangeLock.lock(); try { while (balance < amount) // Wait until the balance becomes //sufficient (i.e., until a deposit is made) } finally{ balanceChangeLock.unlock(); } Call sleep() to wait?

Waiting and Signaling Using a Condition A thread waits on a condition (e.g., balance > 0 ) and another thread signals when the condition becomes true To create a condition –Condition c = balanceChangeLock.newCondition(); To start waiting on a condition –c.await(); To signal that a condition has become true –c.signalAll() or c.signal();

Waiting and Signaling Using a Condition Waiting threads are blocked and will not be considered for execution until the condition is signaled The lock must still be released before they can run Recall: Can also be done with an object’s built-in lock and condition: wait() to wait and notifyAll() or notify() to signal

The BankAccount class with locks and conditions import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; // A bank account has a balance that can be changed by // deposits and withdrawals. public class BankAccount { public BankAccount() { balance = 0; balanceChangeLock = new ReentrantLock(); sufficientFundsCondition = balanceChangeLock.newCondition(); } public void deposit(double amount) { balanceChangeLock.lock(); try { System.out.print("Depositing " + amount); double newBalance = balance + amount; System.out.println(", new balance is " + newBalance); balance = newBalance; sufficientFundsCondition.signalAll(); } finally { balanceChangeLock.unlock(); }

public void withdraw(double amount) throws InterruptedException { balanceChangeLock.lock(); try { while (balance < amount) sufficientFundsCondition.await(); System.out.print("Withdrawing " + amount); double newBalance = balance - amount; System.out.println(", new balance is " + newBalance); balance = newBalance; } finally { balanceChangeLock.unlock(); } public double getBalance() { return balance; } private double balance; private Lock balanceChangeLock; private Condition sufficientFundsCondition; }