Using conditions in synchronized code
A classic problem in concurrent programming is the producer-consumer problem. We have a data buffer, one or more producers of data that save it in the buffer, and one or more consumers of data that take it from the buffer.
As the buffer is a shared data structure, we have to control access to it using a synchronization mechanism, such as the synchronized
keyword, but here we have more limitations. A producer can't save data in the buffer if it's full, and a consumer can't take data from the buffer if it's empty.
For these types of situations, Java provides the wait()
, notify()
, and notifyAll()
methods implemented in the Object
class. A thread can call the wait()
method inside a synchronized
block of code. If it calls the wait()
method outside a synchronized
block of code, JVM throws an IllegalMonitorStateException
exception. When the thread calls the wait()
method, JVM puts the thread to sleep and releases the object that controls the synchronized
block...