BlockingQueue in Java – How to implement producer-consumer design using BlockingQueue?

Java 5 util.concurrent package provides a very useful class named “BlockingQueue” to implement producer-consumer design. In java 1.4 world developers used to use wait and notify mechanism to implement the same design. BlockingQueue class made code more readable and reduced the chances of bug in the code. In the below given example, we have a shared resource which is type of BlockingQueue. BlockingQueue implementation make sure that the producer is made wait if there is no space left in the queue. Also the consumer is made wait if the queue is empty. In this example producer produces something in every one second and consumer consumes what is produced by the producer in every two seconds. Because there are two consumers the producer don’t have to wait in this example. You may remove one consumer or reduce the producer sleep time to test the “Blocking” behavior of the queue.

Important APIs.
  1. void put(E e) throws InterruptedException
  2. E poll();
Complete sample program.