Why does java.lang.Object
have two notify methods - notify
and notifyAll
? It seems that notifyAll
does at least everything notify
does, so why not just use notifyAll
all the time? If notifyAll
is used instead of notify
, is the program still correct, and vice versa? What influences the choice between these two methods?
notify() is used to wake any thread in the wait set whereas notifyAll() is used to wake up all the threads in the waiting set. On a general basis, notifyAll() is used. Even if you are not sure which to use, then you can go ahead and use notifyAll().
Sr. No. In the case of the multiThreading, notify() method sends the notification to only one thread among the multiple waiting threads which are waiting for the send lock. While notifyAll() methods in the same context send notifications to all waiting threads instead of a single thread.
If no threads are waiting in the waiting queue, then notify() and notifyAll() have no effect. Before calling the notify() or notifyAll() method of an object, a thread must own the lock of the object. Hence it must be in one of the object's synchronized methods or synchronized block.
The wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object. The notify() method wakes up a single thread that is waiting on that object's monitor. The notifyAll() method wakes up all threads that are waiting on that object's monitor.
Two typical examples.
Let's say you have a producer thread and a consumer thread. Each "packet" produced by the producer should be consumed by a consumer. The consumer puts something in a queue and then calls notify()
(Only one consumer should be let through to process one "packet".)
Let's say you want to have a notification when a lengthy process has finished. You want a beep and a screen update. The process performs notifyAll()
to notify both the beeping-thread and the screen-update-thread.
According to the JavaDoc for notify
:
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.
This might be useful if you had an application that uses, for example, a queue to place items and then has many worker threads that will pull items off of the queue. When an item is ready, you could call notify
to wake up a single worker to process the item. Admittedly this example is a bit contrived - there are likely better ways to implement this in Java - but you get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With