• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Clarification of notify( ) vs. notifyAll( )

 
Juan Carlos
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic