ArrayBlockingQueue

ArrayBlockingQueue implements BlockingQueue interface. ArrayBlockingQueue is a bounded blocking queue that stores it’s elements in an array internally.

Queue orders elements in FIFO (first-in-first-out) order. The head of the array contains element that has been in the queue for the longest time and tail of the queue contains elements that have been in the queue for the shortest time.

Elements are inserted at tail of the queue and retrieved from the head. Attempts to put an element into a full queue will result in the operation blocking. Attempts to take an element from an empty queue will similarly block.

Fairness

ArrayBlockingQueue supports fairness for ordering waiting producer and consumer threads. By default fairness is turned off. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but avoids starvation.

Here is how we create a ArrayBlockingQueue with fairness enabled. Second argument of the constructor enables/disable fair mode.

BlockingQueue queue = new ArrayBlockingQueue(100, true);
queue.put("Hello");
String out = queue.take();

Constructors

  1. ArrayBlockingQueue​(int capacity) : Creates an ArrayBlockingQueue with the given bounded capacity and default non-fair access policy.
  2. ArrayBlockingQueue​(int capacity, boolean fair) : Creates an ArrayBlockingQueue with the given capacity and the specified access policy.

Important methods

  1. peek() : Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
  2. poll() : Retrieves and removes the head of this queue, or returns null if this queue is empty.
  3. put(E element) : Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.
  4. E take() : Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
  5. size() : Returns the number of elements in this queue.
  6. contains​(Object o) : Returns true if this queue contains the specified element.

References

ArrayBlockingQueue Javadoc

  1. Leave a comment

Leave a comment