1.

What is a Blocking Queue and how does it help solve the producer-consumer problem?

Answer»

Consumer Producer PROBLEM is one in which we have two independent entities – a producer and a consumer sharing a common buffer/queue. Producer writes data to the queue while Consumer CONSUMES from it. The problem is that if queue is full then the producer should wait for space to become available before writing to it while if the queue is empty, the consumer should wait for data to become available before starting to read again.

In a traditional queue, if the queue is full and the producer tries to add more elements to it, it will throw an EXCEPTION. On the other hand, if the queue is empty and the consumer tries to read from it, it will throw an exception again. This is where Blocking Queue is of help.

Blocking Queue is a part of the java.util.concurrent package. It is a type of Queue with the additional feature of blocking if the queue is full or empty. A THREAD trying to add/enqueue an element to an ALREADY full queue is blocked until another thread makes space for it by removing/dequeuing an element from the queue. Similarly, a thread trying to dequeue an element from an empty queue is blocked until another thread adds an element to the queue. Hence in this way, it helps solve the Consumer Producer problem.

The various implementations of BlockingQueue are:

  • LinkedBlockingQueue
  • PriorityBlockingQueue
  • SynchronousBlockingQueue


Discussion

No Comment Found