What is the ArrayBlockingQueue.isEmpty method in Java?

ArrayBlockingQueue is a bounded queue and it is thread-safe. It uses a fixed-size array internally so that its size cannot change after declaration. The elements of this queue follow First-In-First-OutElements are inserted at the end of the queue and retrieved from the head of the queue.. null objects are not allowed as elements in this queue.

The isEmpty method can be used to check if the ArrayBlockingQueue object is empty (contains no element).

Syntax

public boolean isEmpty()

Parameters

This method doesn’t take any arguments.

Return value

This method returns true if the queue contains no elements. Otherwise, false is returned.

Code

The code below demonstrates how to use the isEmpty method.

import java.util.concurrent.ArrayBlockingQueue;
class IsEmpty {
public static void main( String args[] ) {
// Declare a ArrayBlockingQueue with String type elemetns. The size of the queue is set to 5.
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
// Print the Queue. It should be empty
System.out.println("The queue is " + queue);
// Check if the Queue is empty. It should return true
System.out.println("queue.isEmpty() - " + queue.isEmpty());
// Add a string to the queue
queue.add("1");
// Check the queue again
System.out.println("\nAfter adding 1.The queue is " + queue);
// Check if the queue is empty. It should return false
System.out.println("queue.isEmpty() - " + queue.isEmpty());
}
}

Explanation

In the code above:

  • In line 1, we import the ArrayBlockingQueue from the java.util.concurrent package.

  • In line 5, we create an object for the ArrayBlockingQueue class with the name queue and size 5.

  • In line 9, we use the isEmpty method to check if the queue is empty. In our case, true is returned because the queue has no elements.

  • In line 11, we call the add method to add the element "1" to the queue object.

  • In line 15, the isEmpty method returns false because the queue contains 1 element.

Free Resources