What is the ConcurrentLinkedQueue.size() method in Java?
ConcurrentLinkedQueueis 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.nullelements are not allowed in the queue. We can useConcurrentLinkedQueuewhen multiple threads share a single queue.
The size method can be used to get the number of elements present in the ConcurrentLinkedQueue object.
Syntax
public int size()
Parameters
This method doesn’t take any parameters.
Return value
The size method returns an integer value that represents the number of elements present in the queue object.
Code
The code below demonstrates how to use the size method.
import java.util.concurrent.ConcurrentLinkedQueue;class Size {public static void main( String args[] ) {ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();queue.add("1");queue.add("2");queue.add("3");System.out.println("The queue is " + queue);System.out.println("The size of the queue is " + queue.size());}}
Explanation
In the code above:
-
In line 1: We import the
ConcurrentLinkedQueueclass. -
In line 4: We create a
ConcurrentLinkedQueueobject with the namequeue. -
From lines 5 to 7: We use the
add()method of thequeueobject to add three elements ("1","2","3") toqueue. -
In line 10: We use the
size()method of thequeueobject to get the number of elements present in thequeue. In our case,3will be returned.