The Java notify
and notifyAll
basic synchronization tools both require you to synchronize on the object before calling them. This is for a simple safety point since it also requires you to synchronize on them before wait
ing.
For example if you have two threads. One thread reads data from a buffer and one thread writes data into the buffer.
The reading data thread needs to wait until the writing data thread has finished writing a block of data into the buffer and then it can read the block.
If wait()
, notify()
, and notifyAll()
methods can be called without synchronization then you can get a race condition where:
The reading thread calls wait()
and the thread is added to waiting queue.
At the same time, the writing thread calls notify()
to signal it has added data.
The reading thread misses the change and waits forever since the notify()
was processed before the wait()
was.
By forcing the wait
and notify
to happen within a synchronized block this race condition is removed.