Java BlockingQueue Example

By Arvind Rai, January 11, 2023
On this page, we will learn using BlockingQueue interface in our Java application.
1. The BlockingQueue is a Queue with additional capability that are
a. The BlockingQueue waits for the queue to become non-empty when retrieving an element.
b. The BlockingQueue waits for space to become available in the queue when storing an element.

2. The BlockingQueue methods can start its operation either without waiting or with waiting. It offers four types of methods.
a. Throws exception : These methods do not wait to start its operation, if they are unable to start immediately, they throw exception. The methods are add(e), remove() and element().
b. Returns null or false value : These methods return null are false value immediately depending on the operation. These methods are offer(e), poll() and peek().
c. Blocks : These methods block the current thread indefinitely until the operation can succeed. These methods are put(e) and take().
d. Times out : These methods block the current thread only up to given time. The methods are offer(e, time, unit) and poll(time, unit).

3. The BlockingQueue implementation classes are
ArrayBlockingQueue
LinkedBlockingDeque
LinkedBlockingQueue
LinkedTransferQueue
PriorityBlockingQueue
SynchronousQueue
DelayQueue

4. The BlockingQueue does not accept null elements. When we add, put or offer a null value, it throws NullPointerException.

5. The default size of a BlockingQueue is Integer.MAX_VALUE. If we have constructed BlockingQueue with a specified size and if capacity is full, then no element can be put without blocking.

6. The BlockingQueue implementations are thread safe. Their methods are atomic that are handled either by using locks or other forms of concurrency control. However, the bulk operations such as addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation.

7. The BlockingQueue are primarily used for producer-consumer queues.

Producer-Consumer Example

Find the producer-consumer example using BlockingQueue and its implementation class ArrayBlockingQueue with capacity 1. Producer produces element and waits for consumer to consume it. Consumer consumes the element and waits for producer to produce it, and so on.
ProducerConsumer.java
package com.concretepage;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class Producer implements Runnable {
  private final BlockingQueue<String> queue;
  Producer(BlockingQueue<String> q) {
	queue = q;
  }
  public void run() {
	try {
	  while (true) {
		queue.put(produceData());
	  }
	} catch (InterruptedException ex) {
	  System.out.println(ex);
	}
  }
  int cnt = 1;
  String produceData() {
	try {
	  Thread.sleep(2000);
	} catch (InterruptedException e) {
	  e.printStackTrace();
	}
	String s = "A-" + cnt++;
	System.out.println("Produced: " + s);
	return s;
  }
}

class Consumer implements Runnable {
  private final BlockingQueue<String> queue;
  Consumer(BlockingQueue<String> q) {
	queue = q;
  }
  public void run() {
	try {
	  while (true) {
		consumeData(queue.take());
	  }
	} catch (InterruptedException ex) {
	  System.out.println(ex);
	}
  }
  void consumeData(String s) {
	System.out.println("Consumed: " + s);
  }
}

public class ProducerConsumer {
  public static void main(String[] args) {
	int capacity = 1;
	BlockingQueue<String> q = new ArrayBlockingQueue<>(capacity);
	Producer p = new Producer(q);
	Consumer c = new Consumer(q);
	new Thread(p).start();
	new Thread(c).start();
  }
} 
Output
Produced: A-1
Consumed: A-1
Produced: A-2
Consumed: A-2
Produced: A-3
Consumed: A-3
Produced: A-4
Consumed: A-4
------ 

BlockingQueue Methods

The BlockingQueue implements Collection, Iterable and Queue interfaces. Here we will discuss methods declared in BlockingQueue interface.
1. add
boolean add(E e) 
Inserts the specified element into this queue immediately if there is space and returns true.
If no space is currently available, it throws IllegalStateException.
2. put
void put(E e) throws InterruptedException 
Inserts the specified element into this queue and if no space is available, it waits for space to become available.
3. Offer
boolean offer(E e) 
Inserts the specified element into this queue immediately, if space is available. Upon success, it returns true otherwise false.
With timeout:
boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException 
Inserts the specified element into this queue, and if no space is available, it waits up to the specified time. Upon success, it returns true otherwise false.
4. take
E take() throws InterruptedException 
Retrieves and removes the head of this queue, and waits if necessary until an element becomes available.
5. poll
E poll(long timeout, TimeUnit unit) throws InterruptedException 
Retrieves and removes the head of this queue, and if element is not available, it waits up to the specified time to become element available.
6. remove
boolean remove(Object o) 
Removes a single instance of the specified element from this queue, if it is present. Upon success, it returns true otherwise false.
7. drainTo
int drainTo(Collection<? super E> c) 
Removes all available elements from this queue and adds them to the given collection. It returns the number of elements transferred.
With max elements:
int drainTo(Collection<? super E> c, int maxElements) 
Removes at most the given number of available elements from this queue and adds them to the given collection. It returns the number of elements transferred.
8. contains
boolean contains(Object o) 
Returns true if this queue contains the specified element otherwise false.
9. remainingCapacity
int remainingCapacity() 
Returns the number of elements that can be added without blocking it.

Reference

Interface BlockingQueue
POSTED BY
ARVIND RAI
ARVIND RAI











©2023 concretepage.com | Privacy Policy | Contact Us