Wednesday, May 14, 2008

Difference between notify() and notifyAll()

notify(): this method should be called only when the current thread has already acquired the lock on the object. If the wait set of the object is non-empty then a thread from the set is arbitrarily chosen, removed and is re-enabled for thread scheduling. Of course, the thread will not be able to proceed unless the current thread releases the object’s lock.

notifyAll(): it’s same as the notify() method. The only difference is that in this case all the threads from the non-empty wait set of the object are removed and are re-enabled for thread scheduling in stead of only one thread from the wait set being picked arbitrarily, removed, and re-enabled for thread scheduling as is the case in notify() method.


1 comment:

Javin @ java synchronization tutorial said...

Hi, Great post. Just to add while using wait and notify or notifyAll method in Java following things must be remember :

1) use notifyAll instead of notify if you expect more than one thread is waiting for lock.
2)wait() and notify() method must be called from synchronized context, see the link for more detailed explanation.
3) Always call wait() method in loop because if multiple threads are waiting for lock and one of them got lock and reset the condition and other thread needs to check the condition after they got wake up to see whether they need to wait again or can start processing.
4) use same object for calling wait() and notify() method, every object has its own lock so calling wait() on objectA and notify() on object B will not make any sense.