Producer-Consumer Problem in Java using BlockingQueue

The producer consumer problem describes two processes, the producer and consumer, who share a common fixed size buffer used as a queue. The producer generates data and put data into buffer continuously. At the same time, the consumer will be consuming the data continuously. The problem is to make sure that producer won’t try to add data into buffer if it is full and that the consumer won’t try to remove data from an empty buffer. This version of the producer consumer problem is also known as bounded buffer problem. We can also have an unbounded buffer and in that case we have to take care of only the consumer that the consumer won’t try to remove data from an empty buffer. The producer consumer problem is a classic example of a multi-process synchronization problem.

We can easily implement the producer consumer problem using the BlockingQueue. A BlockingQueue already supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. Without BlockingQueue, every time we put data to queue at the producer side, we need to check if queue is full, and if full, wait for some time, check again and continue. Similarly on the consumer side, we would have to check if queue is empty, and if empty, wait for some time, check again and continue. However with BlockingQueue we don’t have to write any extra logic than to just add data from Producer and poll data from Consumer.

Producer-Consumer Example using BlockingQueue

Producer1.java

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.BlockingQueue;

 

class Producer1 extends Thread {

  BlockingQueue<String> bq;

 

  Producer1() {

    bq = new ArrayBlockingQueue<String>(5);

  }

 

  public void run() {

 

      for (int i = 0; i <= 10; i++) {

        try {

          System.out.println("adding str"+i);

          bq.put("str"+i);

          Thread.sleep(1);

        } catch (InterruptedException e) {

        }

    }

  }

}

 

Consumer1.java

import java.util.concurrent.TimeUnit;

 

class Consumer1 extends Thread {

  Producer1 prod;

 

  Consumer1(Producer1 prod) {

    this.prod = prod;

  }

 

  public void run() {

    for(int i=0;i<10;i++)

    {

      try {

        System.out.println("received "+prod.bq.poll(10, TimeUnit.SECONDS));

        Thread.sleep(2000);

      } catch (InterruptedException e) {

      }

    }

  }

}

 

ProducerConsumer1.java

public class ProducerConsumer1 {

  public static void main(String[] args) {

    Producer1 obj1 = new Producer1();

    Consumer1 obj2 = new Consumer1(obj1);

    Thread t1 = new Thread(obj1);

    Thread t2 = new Thread(obj2);

    t2.start();

    t1.start();

  }

}

Change the values in Thread.sleep() in both Producer and Consumer to see how a faster producer and slow consumer work; and how a slow producer and faster consumer work.

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)