This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Clarification of notify( ) vs. notifyAll( ) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Clarification of notify( ) vs. notifyAll( )" Watch "Clarification of notify( ) vs. notifyAll( )" New topic
Author

Clarification of notify( ) vs. notifyAll( )

Juan Carlos
Greenhorn

Joined: Nov 18, 2003
Posts: 1
I am currently studying threads and synchronization. What I have not been able to figure out a detail in the difference between notify and notifyAll.
I read that notifyAll() notifies all the threads that are waiting, and that notify() notifies only one thread waiting. I have no problem understanding who notifyAll() works.
- What if I call notify() and there are several threads waiting?
* How would the system determine what thread must be notified?
* Would it be an error to call notify() if there are several threads waiting?
Thanks in advance for your feedback!!
-Juan Carlos
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi Juan
Welcome to JavaRanch!

- What if I call notify() and there are several threads waiting?

Then only one gets notified. The others stay suspended, and won't wake up until they are notified in turn.

* How would the system determine what thread must be notified?

As it says in the Javadoc, "The choice is arbitrary and occurs at the discretion of the implementation."

* Would it be an error to call notify() if there are several threads waiting?

It depends on the application. notify() might mean that, for example, one unit of work was ready to process; the notified threads might be "worker threads" waiting to do work. So in this case "notifyAll" would clearly be wrong; you'd just want to notify one waiting thread, and the others could stay suspended.


[Jess in Action][AskingGoodQuestions]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Clarification of notify( ) vs. notifyAll( )
 
Similar Threads
Doubt in Thread Chapter
Interrupt method + volatile modifier?
Threads notify ( )
Doubt in Thread Chapter
synchronization - cannot wake a sleeping thread?