Java Reference
In-Depth Information
is released but before the thread is suspended. The notification
would have no effect on the thread, effectively getting lost. When
a thread is restarted after being notified, the lock is atomically
reacquired.
The condition test should always be in a loop. Never assume that
being awakened means that the condition has been satisfiedit
may have changed again since being satisfied. In other words,
don't change the while to an if .
On the other side, the notification methods are invoked by synchronized
code that changes one or more conditions on which some other thread
may be waiting. Notification code typically looks something like this:
synchronized void changeCondition() {
… change some value used in a condition test …
notifyAll(); // or notify()
}
Using notifyAll wakes up all waiting threads, whereas notify picks only
one thread to wake up.
Multiple threads may be waiting on the same object, possibly for differ-
ent conditions. If they are waiting for different conditions, you should
always use notifyAll to wake up all waiting threads instead of using no-
tify . Otherwise, you may wake up a thread that is waiting for a differ-
ent condition from the one you satisfied. That thread will discover that
its condition has not been satisfied and go back to waiting, while some
thread waiting on the condition you did satisfy will never get awakened.
Using notify is an optimization that can be applied only when:
All threads are waiting for the same condition
At most one thread can benefit from the condition being met
This is contractually true for all possible subclasses
 
Search WWH ::




Custom Search