Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

If one Googles for "difference between notify() and notifyAll()" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in notify() and all in notifyAll().

However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.

What's the useful difference between notify() and notifyAll()then? Am I missing something?

1 Answer

0 votes
by (46k points)

However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.

That is not right.  o.notifyAll() calls all of the threads that are prevented in o.wait() calls. The threads are only permitted to return from o.wait() one-by-one, but they all will get their turn.

Just put, it depends on why your threads are anticipating to be notified. Do you require to tell one of the standing threads that something occurred, or do you require to tell all of them at the same time?

In some instances, all waiting threads can take helpful action once the wait finishes. An illustration would be a set of threads expecting for a particular task to finish; once the task has completed, all waiting threads can proceed with their business. In such a situation you would use notifyAll() to wake up all expecting threads at the same time.

Another example, for instance mutually independent locking, only one of the waiting threads can do something valuable after being published (in this instance obtain the lock). In such a case, you would first use notify(). Correctly completed, you could use notifyAll() in this position as well, but you would accidentally wake threads that can't do anything nevertheless.

In many examples, the code to await a situation will be written as a loop:

synchronized(o) {

    while (! IsConditionTrue()) {

        o.wait();

    }

    DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();

}

That way, if an o.notifyAll() call wakes more than one remaining thread, and the first one to pass from the o.wait() makes transmits the condition in the false state, then the extra threads that were awakened will go back to waiting.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...