1000 Java Tips ebook
Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!.
When should I use notify() and when notifyAll() methods on threads?
JavaFAQ Home » Threads
Question: When should I use notify() and
when notifyAll() methods on threads?
Answer: Generally it is more reliable to
use notifyAll() method. Notify() method 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. Since it is internally implemented we do not know exactly
which thread will be chosen.
This method should only be called by a thread that is the owner of this
object's monitor. A thread becomes the owner of the object's monitor in one of
By executing a synchronized instance method of that object.
By executing the body of a synchronized statement that synchronizes on the
For objects of type Class, by executing a synchronized static method of that
Only one thread at a time can own an object's monitor.
It is much safer to use from the beginning notifyAll() method and later
trying to optimize your program you can try to switch to notify(). You have no
idea which thread will be awakened. You must be sure that every waiting thread
will be able to continue if you use notify() method. The behavior of your
program will be more predictable.
From another hand using notify() method will decrease CPU and memory consumption
since just one of multiple thread is awaken and rest are in waiting mode.
Our older tips: March 22, 2001 - October 21, 2002
All published and not published on the site tips read
Printer Friendly Page
Send to a Friend
Search here again if you need more info!