DOC PREVIEW
UMD CMSC 433 - Locks (Java 1.5)

This preview shows page 1-2-19-20 out of 20 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 20 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Locks (Java 1.5)• Only one thread can hold a lock at once– Other threads that try to acquire it block (or becomesuspended) 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 beenreleased same number of times has been acquiredinterface Lock { void lock(); void unlock(); ... /* Some more stuff, also */}class ReentrantLock implements Lock { ... }2Avoiding Interference: Synchronizationpublic class Example extends Thread { private static int cnt = 0; static Lock lock = new ReentrantLock(); public void run() { lock.lock(); try { int y = cnt; cnt = y + 1; } finally { lock.unlock(); } } } …}Lock, for protecting the shared stateAcquires the lock;Only returns when notheld by anotherthreadReleases the lock3Producer/Consumer Design• Suppose we are communicating with a sharedvariable– E.g., some kind of a buffer holding messages• One thread produces input to the buffer• One thread consumes data from the buffer• How do we implement this?– Use condition variables4Conditions (Java 1.5)• Condition created from a Lock• await called with lock held– Releases the lock• But not any other locks held by this thread– Adds this thread to wait set for lock– Blocks the thread• signallAll called with lock held– Resumes all threads on lock’s wait set– Those threads must reacquire lock before continuing• (This is part of the function; you don’t need to do it explicitly)interface Lock { Condition newCondition(); ... }interface Condition { void await(); void signalAll(); ... }Conditionwait set...5 Lock lock = new ReentrantLock(); Condition ready = lock.newCondition(); boolean valueReady = false; Object value;void produce(Object o) { lock.lock(); try { while (valueReady) ready.await(); value = o; valueReady = true; ready.signalAll(); } finally { lock.unlock(); } }Object consume() { lock.lock(); try { while (!valueReady) ready.await(); Object o = value; valueReady = false; ready.signalAll(); } finally { lock.unlock(); }Producer/Consumer Example6Use This Design• This is the right solution to the problem– Tempting to try to just use locks directly– Very hard to get right– Problems with other approaches often very subtle• E.g., double-checked locking is broken7 Lock lock = new ReentrantLock(); boolean valueReady = false; Object value;void produce(object o) { lock.lock(); while (valueReady); value = o; valueReady = true; lock.unlock(); }Object consume() { lock.lock(); while (!valueReady); Object o = value; valueReady = false; lock.unlock(); }Broken Producer/Consumer ExampleThreads wait with lock held – no way to make progress8 Lock lock = new ReentrantLock(); boolean valueReady = false; Object value;void produce(object o) { while (valueReady); lock.lock(); value = o; valueReady = true; lock.unlock(); }Object consume() { while (!valueReady); lock.lock(); Object o = value; valueReady = false; lock.unlock(); }Broken Producer/Consumer ExamplevalueReady accessed without a lock held – race condition9 Lock lock = new ReentrantLock(); Condition ready = lock.newCondition(); boolean valueReady = false; Object value;void produce(object o) { lock.lock(); if (valueReady) ready.await(); value = o; valueReady = true; ready.signalAll(); lock.unlock(); }Object consume() { lock.lock(); if (!valueReady) ready.await(); Object o = value; valueReady = false; ready.signalAll(); lock.unlock(); }Broken Producer/Consumer Examplewhat if there are multiple producers or consumers?10More on the Condition Interface• await(t, u) waits for time t and then gives up– Result indicates whether woken by signal or timeout• signal() wakes up only one waiting thread– Tricky to use correctly• Have all waiters be equal -- use multiple conditions to make thishappen• handle exceptions correctly– Highly recommended to just use signalAll() interface Condition { void await(); boolean await (long time, TimeUnit unit); void signal(); void signalAll();... }11Await and SignalAll Gotcha’s• await must be in a loop– Don’t assume that when wait returns conditions aremet• Avoid holding other locks when waiting– await only gives up locks on the lock that owns theCondition you await on12More locks• ReadWriteLock– holds a pair of coupled locks• a read lock, and• a write lock• Write lock is exclusive: if any thread holds it, nothread can hold any other lock• Read lock is non-exclusive: other threads maysimultaneously acquire locks on the read lock13Blocking Queues in Java 1.5• Interface for producer/consumer pattern• Two handy implementations– LinkedBlockingQueue (FIFO, may be bounded)– ArrayBlockingQueue (FIFO, bounded)– (plus a couple more) interface Queue<E> extends Collection<E> { boolean offer(E x); /* produce */ /* waits for queue to have capacity */ E remove(); /* consume */ /* waits for queue to become non-empty */ ... }14Wait and NotifyAll (Java 1.4)• Recall that in Java 1.4, use synchronize onobject to get associated lock• Objects also have an associated wait setobject oo’s locko’s wait set15Wait and NotifyAll (cont’d)• o.wait()– Must hold lock associated with o– Release that lock• And no other locks– Adds this thread to wait set for lock– Blocks the thread• o.notifyAll()– Must hold lock associated with o– Resumes all threads on lock’s wait set– Those threads must reacquire lock before continuing• (This is part of the function; you don’t need to do it explicitly)16public class ProducerConsumer { private boolean valueReady = false; private Object value; synchronized void produce(Object o) { while (valueReady) wait(); value = o; valueReady = true; notifyAll(); } synchronized Object consume() { while (!valueReady) wait(); valueReady = false; Object o = value; notifyAll(); return o; }}Producer/Consumer in Java 1.417Thread Cancellation• Example scenarios: want to cancel thread– Whose processing the user no longer needs (i.e., shehas hit the “cancel” button)– That computes a partial result and other threadshave encountered errors, … etc.• Java used to have Thread.kill()– But it and Thread.stop() are deprecated– Use Thread.interrupt() instead18Thread.interrupt()• Tries to wake up a thread– Sets the thread’s


View Full Document

UMD CMSC 433 - Locks (Java 1.5)

Documents in this Course
Trace 1

Trace 1

62 pages

Reflection

Reflection

137 pages

Testing

Testing

25 pages

Paradigms

Paradigms

10 pages

Testing

Testing

17 pages

Java RMI

Java RMI

17 pages

Java RMI

Java RMI

17 pages

Java RMI

Java RMI

17 pages

Trace 1

Trace 1

46 pages

Jini

Jini

4 pages

Final

Final

15 pages

Java RMI

Java RMI

13 pages

Testing

Testing

16 pages

Load more
Download Locks (Java 1.5)
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Locks (Java 1.5) and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Locks (Java 1.5) 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?