File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NX: notify() VS notifyAll() ???

 
HaoZhe Xu
Ranch Hand
Posts: 222
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
People usually use notify() and ignore notifyAll() but I have a book it says notifyAll() is better than notify() and it mentions a phrase "miss notification", what does it mean? Is it ture? In the book, it says if there is only one thread waiting, notify() is OK, notifyAll() is OK but it uses more resource than notify(), that's a waste, but if there are more than one thread.
two methods in ClassX

and, there's a class ClassY

If threadA is runing in ClassY, it synchronize cx, invokes wait(), if threadB invokes waitUntilTrue(), it's now waiting, too. if threadC uses setValue(), and pass true (new value), threadC will just notify one thread, because it didn't use notifyAll(), cannot make sure whether threadA or threadB receive the notification.
 
Philippe Maquet
Bartender
Posts: 1872
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi HaoZhe,
People usually use notify() and ignore notifyAll() but I have a book it says notifyAll() is better than notify() and it mentions a phrase "miss notification", what does it mean? Is it ture? In the book, it says if there is only one thread waiting, notify() is OK, notifyAll() is OK but it uses more resource than notify(), that's a waste, but if there are more than one thread.

You have three possible cases :
  • You know that only one thread is waiting to be notified on a given object. In this case, notify() is better because more efficient.
  • You know that multiple threads may be waiting to be notified on a given object, but all threads are interchangeable : you need one of them to perform a job, but it can be *any* of them. In this case, notify() is still better, for the same reasons.
  • Multiple threads may be waiting to be notified on a given object, but they are not interchangeable for two possible reasons : they have a different interest in the notification (that's what happens with locking - each thread may be waiting on a different record lock) or you need to awake all waiting threads for any reason of yours. In that case, notifyAll() *must* be used.


  • Best regards,
    Phil.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic