Producer-Consumer Problem Java Program

In this post we’ll see Java program for producer-consumer problem using threads.

Producer consumer problem

Producer consumer is a classic concurrency problem where synchronization and inter thread communication is required for proper execution.

In producer-consumer problem there are two processes Producer and Consumer sharing a common bounded buffer known as queue.

  • Producer process generates data and insert it into the shared queue.
  • Consumer process consumes data from the shared queue.

The requirement here is that Producer should not try to add data to the shared buffer if it is already full, it should rather wait for the queue to have space for new elements.
Consumer should not try to consume data from an empty buffer, it should wait for data to be inserted in the queue.

Producer-consumer Java program

Since inter-thread communication is required for the proper implementation of Producer-Consumer so this program can be written using wait-notify methods.

You can also make use of the Java concurrency package where many queue implementations are added. Using ArrayBlockingQueue you can easily implement the Producer-Consumer program in Java.

Java program for Producer-consumer using wait-notify

In the Java program a shared buffer is required that is used by both producer and consumer processes for that a LinkedList instance can be used.

There also two Runnable tasks for producer and consumer which are executed by two separate threads. Once a value is added to the queue producer should notify consumer task to wake up and should go to wait state itself.

Same way consumer task should be in wait state if queue is empty.

Output

Java program for Producer-consumer using BlockingQueue

Using a BlockingQueue implementation like ArrayBlockingQueue you can easily implement the Producer-Consumer program in Java.
BlockingQueue has put() method for adding to the queue which blocks if the queue capacity is full. Same way there is a take() method for retrieving from the head of the queue which blocks if there is no element available.

In the code ArrayBlockingQueue of capacity 1 is created so queue will have only one element and the insertion will be blocked until that element is retrieved.

Output

As you can see using ArrayBlockingQueue you don’t need to write logic for synchronizing threads and call wait and notify explicitly making it very simple to write producer-consumer Java program. It can be made more compact using Lambda expression.

That’s all for the topic Producer-Consumer Problem Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.