• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference beteween notify and notifyAll.  RSS feed

 
ram gaurav
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the practical difference beteween notify and notifyAll.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If zero or one threads are waiting on the object, notify() and notifyAll() do the same. If more than one thread is waiting, notify() only wakes up one of them, but notifyAll() wakes up all of them. You can't control which one is woken by notify().

In practice, notifyAll() is used much more often.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I actually use notify() more than notifyAll(). It is rare that I have more than one thread waiting on a given monitor. Instead I usually control very carefully what thread is waiting on a given monitor and don't have to worry about interference because the monitor isn't exposed. Of course, that doesn't mean it's right. I am but an infant in the realm of concurrency.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Same.

I used notifyAll() once long time ago when I created an implementing of MPI (message passing interface) in Java.
 
Henry Wong
author
Sheriff
Posts: 22856
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agreed. There should be very few cases where notifyAll() is needed instead of notify(). The two obvious cases are...

- A condition is in a state that can satisfy multiple threads at the same time.
- The waiting threads are waiting for different conditions, but using the same lock.

With the Lock and Condition classes of Java 5, this second case should no longer apply.

Unfortunately, most of the time, notifyAll() is used, because the developer could not figure out how to get notifications to work correctly.

Henry
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!