What is the ArrayBlockingQueue.add method in Java?

Overview

An ArrayBlockingQueue is a bounded, thread-safe queue. Internally, it uses a fixed-size array. Once the object is created, the size cannot be changed. It also uses FIFO (First-In-First-Out) ordering. Elements are inserted at the end of the queue and retrieved from the head of the queue. Also, null objects are not allowed as elements.

The add method can be used to add an element to the end of the queue. The element will be added only if the queue is not full. Otherwise, an IllegalStateException will be thrown.

Syntax

public boolean add(E e)

Parameters

This method takes the element to be added to the queue as an argument.

Return value

This method returns true if the element is added to the queue successfully.

Code

The code below demonstrates how to use the add method.

import java.util.concurrent.ArrayBlockingQueue;
class Add {
public static void main( String args[] ) {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
queue.add("1");
queue.add("2");
queue.add("3");
queue.add("4");
queue.add("5");
System.out.println("The queue is " + queue);
try{
queue.add("6");
}catch(Exception e) {
System.out.println("Exception on adding 6th element" + e);
}
}
}

Explanation

In the above code,

  • We imported the ArrayBlockingQueue from the java.util.concurrent package.

  • We created an object for the ArrayBlockingQueue class with the name queue and size 5.

  • We added five elements to the queue object, and now the queue is full.

  • We tried adding 6th element to the queue. The queue is already full, so an IllegalStateException is thrown.

Free Resources