Deadlocks

Chapter 8 - Inter-thread Communication

Java Thread Programming
Paul Hyde
  Copyright 1999 Sams Publishing

When to Use notifyAll() Instead of notify()
The fundamental difference between notify() and notifyAll() is that if more than one thread is simultaneously waiting for notification, notify() will provide notification to only one of the waiting threads, whereas notifyAll() will provide notification to all of them. If your code is well defended against early notifications (discussed later), notifyAll() is generally the better choice.
The major disadvantage of notifyAll() is that it is wasteful of processor resources if all but one of the notified threads will end up waiting again. This is a situation that is difficult to guarantee. If your code synchronizes on this either through synchronized blocks or the synchronized method modifier, you cant be sure that some code external to the class wont synchronize and wait on a reference to the object. If that happens, notify() might signal the thread running that external code instead of the thread that you intended. Consider a situation where you have a class, ClassX , with two methods :
public synchronized void waitUntilTrue()
                throws InterruptedException {
    while ( value == false) {
        wait();
    }
}
public synchronized void setValue(boolean newValue) {
    if (newValue != value) {
        value = newValue;
        notify();   // notifyAll() might be safer...
    }
}
In addition, theres an external class, ClassY , with this code in one of its methods:
ClassX cx = new ClassX();
cx.setValue(false);
// ...
synchronized (cx) {
    cx.wait(); // trouble
}
If threadA is running inside ClassY , it synchronizes on cx and invokes wait() . If threadB invokes waitUntilTrue() , it is now also waiting for notification. If threadC invokes setValue() and passes true (a new value), threadC will only notify one thread because notifyAll() wasnt used. Theres no way to be sure whether threadA or threadB will be notified. In this situation, notifyAll() would have guaranteed that they would both be notified.
It is generally safe to use notify() only when you can guarantee that only one thread will ever be waiting for notification. This is a relatively unusual occurrence.
  Tip If youre not sure whether you need to use notify() or notifyAll() , use notifyAll() . It might be a little wasteful, but its safer.

Toc


Java Thread Programming
Java Thread Programming
ISBN: 0672315858
EAN: 2147483647
Year: 2005
Pages: 149
Authors: Paul Hyde

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net