Docsity

Avoiding Interference: Synchronization in Implementation Lock | CMSC 330, Study notes of Programming Languages

Toggle sidebar
bg1
1
CMSC 330, Fall 2005 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 more stuff, also */
}
class ReentrantLock implements Lock { ... }
CMSC 330, Fall 2005 2
Avoiding Interference: Synchronization
public class Example extends Thread {
private static int cnt = 0;
static Lock lock = new ReentrantLock();
public void run() {
lock.lock();
int y = cnt;
cnt = y + 1;
lock.unlock();
}
}
…
}
Lock, for protecting
the shared state
Acquires the lock;
Only succeeds if not
held by another
thread
Releases the lock
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Avoiding Interference: Synchronization in Implementation Lock | CMSC 330 and more Study notes Programming Languages in PDF only on Docsity!

CMSC 330, Fall 2005 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 more stuff, also / } class ReentrantLock implements Lock { ... } CMSC 330, Fall 2005 2

Avoiding Interference: Synchronization

public class Example extends Thread { private static int cnt = 0; static Lock lock = new ReentrantLock(); public void run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } } … }

Lock , for protecting

the shared state

Acquires the lock;

Only succeeds if not

held by another

thread

Releases the lock

CMSC 330, Fall 2005 3

Producer/Consumer Design

• Suppose we are communicating with a shared

variable

  • 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 variables CMSC 330, Fall 2005 4

Conditions (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(); ... }

Condition

wait set

CMSC 330, Fall 2005 7 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 Example

Threads wait with lock held – no way to make progress

CMSC 330, Fall 2005 8 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 Example

valueReady accessed without a lock held – race condition

CMSC 330, Fall 2005 9 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 Example

what if there are multiple producers or consumers?

CMSC 330, Fall 2005 10

More 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, handle exceptions correctly
  • Highly recommended to just use signalAll() interface Condition { void await(); boolean await (long time, TimeUnit unit); void signal(); void signalAll(); ... }

CMSC 330, Fall 2005 13

Wait and NotifyAll (Java 1.4)

• Recall that in Java 1.4, use synchronize on

object to get associated lock

• Objects also have an associated wait set

object o

o’s lock

o’s wait set

CMSC 330, Fall 2005 14

Wait 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)

CMSC 330, Fall 2005 15 public 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.

CMSC 330, Fall 2005 16

Thread Cancellation

• Example scenarios: want to cancel thread

  • Whose processing the user no longer needs (i.e., she

has hit the “cancel” button)

  • That computes a partial result and other threads

have encountered errors, … etc.

• Java used to have Thread.kill()

  • But it and Thread.stop() are deprecated
  • Use Thread.interrupt() instead

CMSC 330, Fall 2005 19

InterruptedException

• Exception thrown if interrupted on certain ops

  • wait, await, sleep, join, and lockInterruptibly
  • Also thrown if call one of these with interrupt flag set

• Not thrown when blocked on 1.4 lock or I/O

class Object { void wait() throws IE; ... } interface Lock { void lock(); void lockInterruptibly() throws IE; ... } interface Condition { void await() throws IE; void signalAll(); ... }