Java Reference
In-Depth Information
Let thread
t
be the thread executing the
wait
method on object
m
, and let
n
be the number of
lock actions by
t
on
m
that have not been matched by unlock actions. One of the following
actions occurs:
• If
n
is zero (i.e., thread
t
does not already possess the lock for target
m
), then an
Il-
legalMonitorStateException
is thrown.
• If this is a timed wait and the
nanosecs
argument is not in the range of
0-999999
or
the
millisecs
argument is negative, then an
IllegalArgumentException
is thrown.
• If thread
t
is interrupted, then an
InterruptedException
is thrown and
t
's interruption
status is set to false.
• Otherwise, the following sequence occurs:
1.
Thread
t
is added to the wait set of object
m
, and performs
n
unlock actions on
m
.
2.
Thread
t
does not execute any further instructions until it has been removed
from
m
's wait set. The thread may be removed from the wait set due to any one
of the following actions, and will resume sometime afterward:
♦ A
notify
action being performed on
m
in which
t
is selected for removal from
the wait set.
♦ A
notifyAll
action being performed on
m
.
♦ An
interrupt
action being performed on
t
.
♦ If this is a timed wait, an internal action removing
t
from
m
's wait set that oc-
curs after at least
millisecs
milliseconds plus
nanosecs
nanoseconds elapse since
the beginning of this wait action.
♦ An internal action by the implementation. Implementations are permitted, al-
though not encouraged, to perform “spurious wake-ups”, that is, to remove
threads from wait sets and thus enable resumption without explicit instructions
to do so.
Notice that this provision necessitates the Java coding practice of using
wait
only within loops that terminate only when some logical condition that the
thread is waiting for holds.
Each thread must determine an order over the events that could cause it to be
removed from a wait set. That order does not have to be consistent with other
orderings, but the thread must behave as though those events occurred in that
order.