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).
public boolean isEmpty()
This method doesn’t take any arguments.
This method returns true
if the queue contains no elements. Otherwise, false
is returned.
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());}}
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.