synchronized (class-instance) { code-block }
class blob {
private int cnt;
void addOne(Object o) {
synchronized (o) { cnt++; }
}
This is legal, but dumb, code.
void f() {
synchronized (this) {
// f's body
}
}
synchronized indicates a synchronized method.
class counter
private int counter = 0
public synchronized int
increase()
System.out.println(value())
count++
public synchronized void
value()
return count
increase() still holds the lock after the value() call.
synchronized void
get() {
// wait until count is positive.
count--
}
get()?
while (count < 1) { }?
wait(), notify(), and notifyAll()
manipulate the wait set.
wait() moves the calling thread to the wait set.
notify() moves a thread, if any, from the wait set to
the mutex.
notifyAll() moves all threads from the wait set to
the mutex.
wait(), notify(), and notifyAll() must be called from within a
synchronized block.
void bad() while (!condition)wait()// what wait set? synchronized void good() while (!condition) wait()
class TroubleAlert
synchronized void whenYellow
while (alert != yellow) wait()
synchronized void whenOrange
while (alert != Orange) wait()
void setYellow
alert = yellow
notify()
notifyAll(), which is
expensive).
notify() unblocks an arbitrary thread in the wait set.
notifyAll() threads is high.
notify() may unblock the wrong thread; tends to deadlock.
notifyAll() is more important than it should be.
if (!buffer_full) wait();
while (!buffer_full) wait();
buffer_full true.
class buffer
private boolean buffer_full = false
private Object buffer
public synchronized void
put(Object o)
while (buffer_full) wait()
buffer = 0
buffer_full = true
notify()
public synchronized Object
get()
while (!buffer_full) wait()
Object o = buffer
buffer_full = false
notify()
return o
synchronized code.
wait(), notify(), and notifyAll() provide conditional
synchronization.
This page last modified on 1 July 2003.