Monday, April 30, 2007

Explain wait(),notify(), and notifyAll() methods?

These methods are used for thread intercommunication and usually called within synchronised block or methods.A thread with lock on the object when calls wait() then it goes into wait state till some other thread with lock on this object invokes notify() method or the notifyAll() method.

1 comments :

JP @ java synchronized keyword on June 3, 2011 at 6:43 AM said...

Hi, 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.

 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker