Producer Consumer Problem Java : Detailed Explaination

Producer Consumer Problem is well-known example of multi-process synchronization problem. It is described as synchronization problem over a fixed size data buffer implemented as queue being modified by two or more different processes referred as producers and consumers. For a data buffer, we can have multiple number of producers and consumers. Producers task is to keep generating data and place it into buffer while Consumers task is to keep consuming data from buffer. Problem is to ensure that Producers do not add data into buffer if its full and Consumer do not consumer data if buffer is empty.

PCP_AndroidSRC.net

For resolving above problem, Producer and Consumer should behave as below.

Producer

1. Check if Buffer is full or not. If full, then wait() for buffer items to get consumed.

2. Generate data and put it into Buffer.

3. Notify Consumer that Data has been placed into Buffer.

4. Repeat step 1-3

Consumer

1. Check if Buffer has items. If empty, then wait() for buffer to get filled.

2. Consume data from Buffer.

3. Notify Producer that Data has been consumed from Buffer

4. Repear step 1-3

We will implement Producer Consumer Problem Java using two approaches.

1. Synchronized Instance Methods

A synchronized instance method in Java is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a synchronized instance method.

Producer Consumer Problem Java Source Code Using Synchronized Instance Methods

2. BlockingQueue (java.util.concurrent.BlockingQueue)

BlockingQueues are thread-safe. They wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element. For this purpose we will use put() to add data to buffer and take() to remove data from buffer.

Producer Consumer Problem Java Source Code Using BlockingQueue

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *