Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple threads wait on one object at once?

If wait can only be called from a synchronized context, and you can only call wait on an object while holding its lock, then how can multiple threads wait on the same object? Furthermore, since notify must also be called from a synchronized context, how can the notify occur?

like image 505
alexgolec Avatar asked Dec 27 '22 22:12

alexgolec


2 Answers

The wait method releases the lock on the object on which it is waiting. Once released, another object can then acquire the lock and also wait or notify. And, this is all right there in the javadoc.

like image 71
jtahlborn Avatar answered Jan 09 '23 06:01

jtahlborn


Not a direct answer to your question, but instead of using the wait method, you could use the CountDownLatch class in the concurrent package introduce on Java 5. You can initialize the CountDownLatch on the class you are going to wait for, and methods waiting for it should execute the method await(), and to release the latch you invoke the method countDown(). It is more clean and clear than using wait() in my opinion. The Effective Java book has a really interesting topic about this class.

like image 42
Ravi Wallau Avatar answered Jan 09 '23 05:01

Ravi Wallau