Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Nigel Shrin
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Henry Wong
author
Marshal
Pie
Posts: 20990
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Nigel Shrin
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Henry, that's a very clear reply, much appreciated.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic