What is the ConcurrentLinkedQueue.isEmpty() method in Java?
The ConcurrentLinkedQueue is a thread-safe unbounded queue. The elements are ordered by FIFO (First-In-First-Out). The elements are inserted at the tail (end) and retrieved from the head (start) of the queue. The null elements are not allowed as an element of the queue. We can use the ConcurrentLinkedQueue when multiple threads are sharing a single Queue.
The isEmpty method can be used to check if the ConcurrentLinkedQueue object has no elements.
Syntax
public boolean isEmpty()
Parameters
This method does not take any arguments.
Return value
This method returns true if the queue object has no elements. Otherwise, it returns false.
Code
The code below demonstrates how to use the isEmpty method.
import java.util.concurrent.ConcurrentLinkedQueue;class IsEmpty{public static void main( String args[] ) {ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();System.out.println("The queue is : " + queue);System.out.println("Check if the queue is empty : " + queue.isEmpty());queue.add("1");System.out.println("\nThe queue is : " + queue);System.out.println("Check if the queue is empty : " + queue.isEmpty());}}
Explanation
In the code above:
-
In line 1, we import the
ConcurrentLinkedQueueclass. -
In line 4, we create a
ConcurrentLinkedQueueobject with the namequeue. This object doesn’t have any elements in it. -
In line 6, we call the
isEmptymethod on thequeueobject. This method will returntruebecause thequeueobject is empty. -
In line 8, we use the
add()method of thequeueobject to add one element ("1") toqueue. -
In line 10, we call the
isEmptymethod on thequeueobject. This method will returnfalsebecause thequeueobject contains one element.