Tuesday, 28 June 2016

Why wait, notify and notifyAll called from synchronized block or method in Java?

If we don't call wait() or notify() method from synchronized method/block, it will throw the "java.lang.IllegalMonitorStateException: current thread not owner".

For example, one thread read data from a buffer and one thread write data into buffer. The reading data thread needs to wait until the writing data thread completely writes a block data into the buffer. The writing data thread needs to wait until the reading data thread completely read the data from the buffer.

If wait(), notify(), and notifyAll() methods can be called by ordinary method, the reading thread calls wait() and the thread is being added to waiting queue. At the same moment, the writing thread calls notify() to signal the condition changes. The reading thread misses the change and waits forever. Hence, they must be called inside a synchronized method or block which is mutually exclusive.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...