Java BlockingQueue Interface

Category: Java   Tags: Java, Java Thread, Java MultiThread, Thread Synchronization, Immutable Objects

It is an extension of java.util.Queue. It 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. BlockingQueue implementations are thread-safe.

BlockingQueue methods can be categorized in four categories:

  • Methods that throws an exception.
  • Methods that returns a special value (either null or false) depending on the operation.
  • Methods that blocks the current thread indefinitely until the operation can succeed.
  • Methods that blocks for a given maximum time limit before it leave.
Below table summarize all these method category wise:

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable

Methods

boolean add(E element)
Inserts the element into the queue if it is not violating capacity restrictions. Returns true upon success.
void put(E element) throws InterruptedException
Inserts the element into the queue. It will wait if no space is available.
E take( ) throws InterruptedException
It retrieves and removes the head of queue. It can wait if necessary until an element becomes available.
boolean offer(E e)
Inserts the element into the queue if it is not violating capacity restrictions. Returns true upon success and false if no space is currently available. When using a capacity-restricted queue, this is preferable to add(E).
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException
Inserts the element into the queue. It waits till specified time if necessary for space to become available.
boolean contains(Object element)
It retrieves and removes the head of queue. It waits till specified time if necessary for space to become available.
E poll(long timeout, TimeUnit unit) throws InterruptedException
It retrieves and removes the head of queue. It waits till specified time if necessary for space to become available.
boolean remove(Object element)
Returns true if this queue contains the element.

Classes

BlockingQueue are implemented by many classes:

  • ArrayBlockingQueue
  • DelayQueue
  • LinkedBlockingDeque
  • LinkedBlockingQueue
  • LinkedTransferQueue
  • PriorityBlockingQueue
  • SynchronousQueue
Here is one example of BlockingQueue using ArrayBlockingQueue:

JavaBlockingQueueExample.java

                            package com.tutorial.javabasic;

                            import java.util.concurrent.ArrayBlockingQueue;
                            import java.util.concurrent.BlockingQueue;

                            class Producer implements Runnable {

                                private final BlockingQueue queue;

                                Producer(BlockingQueue q) {
                                    queue = q;
                                }

                                public void run() {
                                    try {
                                        for (int i = 0; i < 10; i++) {
                                            System.out.println("Producing: " + i);
                                            queue.put(i);
                                        }
                                    } catch (InterruptedException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }

                            class Consumer implements Runnable {

                                private final BlockingQueue queue;

                                Consumer(BlockingQueue q) {
                                    queue = q;
                                }

                                public void run() {
                                    try {
                                        while (true) {
                                            System.out.println("Consuming: " + queue.take());
                                        }
                                    } catch (InterruptedException ex) {
                                        ex.printStackTrace();
                                    }
                                }

                            }

                            class JavaBlockingQueueExample {

                                public static void main(String s[]) {
                                    BlockingQueue queue = new ArrayBlockingQueue(10);
                                    Producer producer = new Producer(queue);
                                    Consumer consumer = new Consumer(queue);
                                    new Thread(producer).start();
                                    new Thread(consumer).start();
                                }
                            }
                        

Output:

                            Producing: 0
                            Producing: 1
                            Producing: 2
                            Producing: 3
                            Producing: 4
                            Producing: 5
                            Producing: 6
                            Producing: 7
                            Producing: 8
                            Consuming: 0
                            Producing: 9
                            Consuming: 1
                            Consuming: 2
                            Consuming: 3
                            Consuming: 4
                            Consuming: 5
                            Consuming: 6
                            Consuming: 7
                            Consuming: 8
                            Consuming: 9