Java Reference
In-Depth Information
would have it,
take
already holds that lock, which it needed to test the condition predicate
(and if the condition predicate was true, to modify the buffer state in the same atomic op-
eration). The
wait
method releases the lock, blocks the current thread, and waits until the
specified timeout expires, the thread is interrupted, or the thread is awakened by a notifica-
tion. After the thread wakes up,
wait
reacquires the lock before returning. A thread waking
up from
wait
gets no special priority in reacquiring the lock; it contends for the lock just
like any other thread attempting to enter a
synchronized
block.
Every call to
wait
is implicitly associated with a specific
condition predicate
. When calling
wait
regarding a particular condition predicate, the caller must already hold the lock asso-
ciated with the condition queue, and that lock must also guard the state variables from which
the condition predicate is composed.
14.2.2. Waking Up Too Soon
As if the three-way relationship among the lock, the condition predicate, and the condition
queue were not complicated enough, that
wait
returns does not necessarily mean that the
condition predicate the thread is waiting for has become true.
Asingleintrinsicconditionqueuemaybeusedwithmorethanoneconditionpredicate.
When
your thread is awakened because someone called
notifyAll
, that doesn't mean that the
condition predicate
you
were waiting for is now true. (This is like having your toaster and
coffee maker share a single bell; when it rings, you still have to look to see which device
When control re-enters the code calling
wait
, it has reacquired the lock associated with
the condition queue. Is the condition predicate now true? Maybe. It might have been true at
the time the notifying thread called
notifyAll
, but could have become false again by the
time
you
reacquire the lock. Other threads may have acquired the lock and changed the ob-
ject's state between when your thread was awakened and when
wait
reacquired the lock. Or
maybe it hasn't been true at all since you called
wait
. You don't know why another thread
called
notify
or
notifyAll
; maybe it was because
another
condition predicate associ-
ated with the same condition queue became true. Multiple condition predicates per condition
queue are quite common—
BoundedBuffer
uses the same condition queue for both the
“not full” and “not empty” predicates.
[9]