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 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 emptySystem.out.println("The queue is " + queue);// Check if the Queue is empty. It should return trueSystem.out.println("queue.isEmpty() - " + queue.isEmpty());// Add a string to the queuequeue.add("1");// Check the queue againSystem.out.println("\nAfter adding 1.The queue is " + queue);// Check if the queue is empty. It should return falseSystem.out.println("queue.isEmpty() - " + queue.isEmpty());}}
Explanation
In the code above:
-
In line 1, we import the
ArrayBlockingQueuefrom thejava.util.concurrentpackage. -
In line 5, we create an object for the
ArrayBlockingQueueclass with the namequeueand size 5. -
In line 9, we use the
isEmptymethod to check if the queue is empty. In our case,trueis returned because the queue has no elements. -
In line 11, we call the
addmethod to add the element"1"to thequeueobject. -
In line 15, the
isEmptymethod returnsfalsebecause the queue contains 1 element.