File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes notify() and notifyAll() - when to use notify()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "notify() and notifyAll() - when to use notify()?" Watch "notify() and notifyAll() - when to use notify()?" New topic
Author

notify() and notifyAll() - when to use notify()?

Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140
If notify() does not take a thread name/number as an arg, then you cannot predict which it will target. Therefore mostly notifyAll() is used.
So, when would you use notify()? only when one thread has been started?

Thank you

// amended: sorry missed out "not" (fourth word)


Nigel
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18765
    
  40

Nigel Shrin wrote:If notify() does take a thread name/number as an arg, then you cannot predict which it will target. Therefore mostly notifyAll() is used.
So, when would you use notify()? only when one thread has been started?


Using notifyAll() when you want to wake up only one thread, and you can't wake up the correct thread, is clearly a bad design. All threads waiting on an object, should all be waiting for the same condition. Do not share condition variables !!

Prior to Java 5, the only case that was a problem was when you needed two condition variables that shared the same lock. This has been remedied in Java 5, with the Lock and Condition classes -- you can now have many condition variables that share the same lock.


So... to answer your question. You use the notify() method when you need to wake up one thread. You use the notifyAll() method when you need to wake up all of the thread (or a number that can't be determined at time of notification). Using the notifyAll() method, because you can't get the notify() method working correctly, is *not* the norm, and should be considered a design bug.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Nigel Shrin
Ranch Hand

Joined: May 18, 2009
Posts: 140
Thank you Henry, that's a very clear reply, much appreciated.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: notify() and notifyAll() - when to use notify()?