Producer Consumer Problem in JAVA using wait() and notify()

This is also known as bounded-buffer problem and classical example of multi-thread/multi-process synchronization problem. This problem sometime plays crucial role during java interview if you are not familiar with proper understanding.  

Scenario is, There is single buffer where Producer writes some data and waits for Consumer to read it. Consumer reads the data from buffer and waits for more data to be available. This situation continuous to go on same way further.

Now Producer has to wait until Consumer finished before it writes more data. And same way, After read, Consumer has to wait until Producer produces more data. This wait is implemented using "Polling". Polling is usually implemented by loop that is used to check some condition repeatedly. Once condition is met appropriate action is taken. "Polling" waste CPU time.

This Polling can be avoided by using wait(), notify() and notifyAll() method. These method are implemented as final method in Object class, so every java class have them. These methods can only be called from synchronized context. So use these three methods to avoid polling.

  1. wait()  : Tells calling thread to give up monitor and to go sleep until some other thread enters same monitor and calls notify.
  2. notify() : wakes up first thread that called wait() on same monitor(object).
  3. notifyAll()  : wakes up all thread that called wait() on same object(monitor), Now OS will decide which thread will execute first based on parameters like Priority etc.
Below is simplest example of implementation.





Output:
$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
Producer :: Write Data :1
Consumer :: Read Data :1
Producer :: Write Data :2
Consumer :: Read Data :2
Producer :: Write Data :3
Consumer :: Read Data :3
Producer :: Write Data :4
Consumer :: Read Data :4
Producer :: Write Data :5
Consumer :: Read Data :5
...

Final note :
Producer & Consumer can be in same process running on different thread or may be on different process as well. So is a multiple thread or multiple process synchronization problem. Wrong implementation can result in deadlock where both are waiting for each other. This problem can be generalized for multiple Producers and Consumers.

Comments

  1. Nice and simple article, made easier to understand.

    ReplyDelete

Post a Comment