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.

Similar presentations

Presentation on theme: "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."— Presentation transcript:

1
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 }

8
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

9
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?

10
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();

11
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