Java Reference
In-Depth Information
public void run () {
synchronized ( theManifest ) {
// read the manifest from the stream in...
theManifest . notify ();
}
// read the rest of the stream...
}
Waiting and notification are more commonly used when multiple threads want to wait
on the same object. For example, one thread may be reading a web server logfile in which
each line contains one entry to be processed. Each line is placed in a java.util.List
as it's read. Several threads wait on the List to process entries as they're added. Every
time an entry is added, the waiting threads are notified using the notifyAll() method.
If more than one thread is waiting on an object, notifyAll() is preferred, because there's
no way to select which thread to notify. When all threads waiting on one object are
notified, all will wake up and try to get the lock on the object. However, only one can
succeed immediately. That one continues; the rest are blocked until the first one releases
the lock. If several threads are all waiting on the same object, a significant amount of
time may pass before the last one gets its turn at the lock on the object and continues.
It's entirely possible that the object on which the thread was waiting will once again have
been placed in an unacceptable state during this time. Thus, you'll generally put the call
to wait() in a loop that checks the current state of the object. Do not assume that just
because the thread was notified, the object is now in the correct state. Check it explicitly
if you can't guarantee that once the object reaches a correct state it will never again reach
an incorrect state. For example, this is how the client threads waiting on the logfile
entries might look:
private List < String > entries ;
public void processEntry () {
synchronized ( entries ) { // must synchronize on the object we wait on
while ( entries . isEmpty ()) {
try {
entries . wait ();
// We stopped waiting because entries.size() became non-zero
// However we don't know that it's still non-zero so we
// pass through the loop again to test its state now.
} catch ( InterruptedException ex ) {
// If interrupted, the last entry has been processed so
return ;
}
}
String entry = entries . remove ( entries . size ()- 1 );
// process this entry...
}
}
Search WWH ::




Custom Search