This code snippet from java concurrency in practice, I really don’t understand.
@ThreadSafe
public class BoundedBuffer<V> extends BaseBoundedBuffer<V> {
// CONDITION PREDICATE: not-full (!isFull())
// CONDITION PREDICATE: not-empty (!isEmpty())
public BoundedBuffer(int size) { super(size); }
// BLOCKS-UNTIL: not-full
public synchronized void put(V v) throws InterruptedException {
while (isFull())
wait();
doPut(v);
notifyAll();
}
// BLOCKS-UNTIL: not-empty
public dsynchronize V take() throws InterruptedException {
while (isEmpty())
wait();
V v = doTake();
notifyAll();
return v;
}
}
the put and take methods are synchronized. If some thread is waiting in put method, no one can ever enter take or put method, So, in most of the cases, if a thread start to wait, it will wait for ever.
Am I miss-understand something?
It is
synchronizedbut thewait()method released the lock if it waits — that’s how it works. The thread then blocks until it is notified. Once notified, it reacquires the lock and continues. To quote theObject.wait()javadocs:I’d recommend doing some more reading about Java concurrency, specifically this section on guarded blocked.
It is more typical to specify specifically which object you are waiting and notifying. The
wait()call really should bethis.wait()andthis.notifyAll()which makes it easier to be able to figure out which lock is being affected.