Monitor Mechanics
Doug Lea - 2nd Edition
-
Implementing guarded methods
-
for each condition that needs to be waited on, write a guarded
wait loop that causes the current thread to block if the guard condition
is false
-
ensure that every method causing state changes that affect
the truth value of any waited-for condition notifies threads waiting for
state changes, causing them to wake up and recheck their guard conditions
-
each object has a lock and also has a "wait set" (which is
maintained internally by the JVM) that is manipulated by wait, notify,
notifyAll, and Thread.interrupt.
-
wait actions:
-
if the current thread has been interrupted, then the method
exits immediately, throwing an InterruptedException. otherwise the current
thread is blocked.
-
the JVM places the thread in the internal wait set
-
the synchronization lock is released, but all other locks
are retained by the thread.
-
notify actions:
-
an arbitrary thread is removed (by the JVM) from the internal
wait set
-
the chosen thread must re-obtain the synchronization lock
for the target object, which will always cause it to block at least until
the thread calling notify releases the lock.
-
the chosen thread is then resumed from the point of its wait
-
notifyAll actions
-
removes all threads from the wait set (simultaneously), but
each thread still has to acquire the lock
-
Interrupt actions
-
if Thread.interrupt is invoked for a thread suspended
on a wait, the same notify mechanics apply, except that after
re-acquiring the lock, the method throws an InterruptedException
and the thread's interruption status is set to false.
-
Timed Waits
-
when wait takes an argument of how much time can elapse
before the wait is aborted, there is no status indication differentiating
waits that return via notifications vs. time-outs.
-
a time wait may resume at an arbitrary amount of time after
the time-out has expired
-
Thread.sleep(long msecs) uses a timed wait but does
not tie up the current object's synchronization lock
-
Interrupted Waits
-
a wait will be broken if the waiting thread has been interrupted.
-
enables blocked threads to respond to thread cancellation
-
most common response is to rethrow interruptedException
to denote failure to the client