Java Reference
In-Depth Information
14.2.3. Missed Signals
Chapter 10 discussed liveness failures such as deadlock and livelock. Another form of live-
ness failure is missed signals . A missed signal occurs when a thread must wait for a spe-
cific condition that is already true, but fails to check the condition predicate before waiting.
Now the thread is waiting to be notified of an event that has already occurred. This is like
starting the toast, going out to get the newspaper, having the bell go off while you are out-
side, and then sitting down at the kitchen table waiting for the toast bell. You could wait a
long time—potentially forever. [10] Unlike the marmalade for your toast, notification is not
“sticky”—if thread A notifies on a condition queue and thread B subsequently waits on that
same condition queue, B does not immediately wake up—another notification is required to
wake B . Missed signals are the result of coding errors like those warned against in the list
above, such as failing to test the condition predicate before calling wait . If you structure
your condition waits as in Listing 14.7 , you will not have problems with missed signals.
14.2.4. Notification
So far, we've described half of what goes on in a condition wait: waiting. The other half is
notification. In a bounded buffer, take blocks if called when the buffer is empty. In order for
take to unblock when the buffer becomes nonempty, we must ensure that every code path
in which the buffer could become nonempty performs a notification. In BoundedBuffer ,
there is only one such place—after a put . So put calls notifyAll after successfully
adding an object to the buffer. Similarly, take calls notifyAll after removing an element
to indicate that the buffer may no longer be full, in case any threads are waiting on the “not
full” condition.
Whenever you wait on a condition, make sure that someone will perform a notification
whenever the condition predicate becomes true.
There are two notification methods in the condition queue API— notify and notifyAll .
To call either, you must hold the lock associated with the condition queue object. Calling
notify causes the JVM to select one thread waiting on that condition queue to wake up;
calling notifyAll wakes up all the threads waiting on that condition queue. Because you
must hold the lock on the condition queue object when calling notify or notifyAll , and
waiting threads cannot return from wait without reacquiring the lock, the notifying thread
should release the lock quickly to ensure that the waiting threads are unblocked as soon as
possible.
Search WWH ::




Custom Search