Java - Collection Framework Blocking Queues

Introduction

A blocking queue extends the behavior of a queue in dealing with empty queue an full queue.

BlockingQueue interface represents a blocking queue. BlockingQueue interface inherits from the Queue interface.

A blocking queue does not allow a null element.

A blocking queue can be bounded or unbounded.

remainingCapacity() returns the number of elements that can be added to the blocking queue without blocking.

The BlockingQueue interface and all its implementation classes are in the java.util.concurrent package.

Fair BlockingQueue deals with the waiting threads by arriving order, unfair queue does not the arriving order.

The following are the implementation classes for the BlockingQueue interface:

Implementation
Description
ArrayBlockingQueue


BlockingQueue backed by an array.
It lets you specify the fairness of the blocking queue in its constructor.
By default, it is not fair.
LinkedBlockingQueue

It can be used as a bounded or unbounded blocking queue.
It does not allow specifying a fairness rule for the blocking queue.
PriorityBlockingQueue


an unbounded implementation class for BlockingQueue.
It works the same way as PriortyQueue for ordering the elements in the blocking queue.
It adds the blocking feature to PriorityQueue.
SynchronousQueue

It does not have any capacity.
The put operation waits for the take operation to take the element being put.
DelayQueue

It is unbounded implementation class for BlockingQueue.
It allows an element to be taken out only if a specified delay has passed for that element.

Related Topics