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 of code that it's executing and allows other threads to execute other blocks of synchronized code protected by this object. To wake up the thread, you must call the notify() or notifyAll() methods inside a block of code protected by the same object.

In this recipe, you will learn how to implement the producer-consumer problem using the synchronized keyword and the wait(), notify(), and notifyAll() methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.19.75