What is the ConcurrentLinkedQueue.remove() method in Java?
Overview
The remove() method of the ConcurrentLinkedQueue class retrieves and removes the ConcurrentLinkedQueue object.
ConcurrentLinkedQueueis a thread-safe, unbounded queue.
The elements are ordered by First-In-First-Out (FIFO). The elements are inserted at the tail (end) and retrieved from the head (start) of the queue.
null elements are not allowed as elements of the queue.
We use the ConcurrentLinkedQueue when multiple threads share a single queue.
Syntax
public E remove()
Parameters
This method doesn’t take any arguments.
Return value
The remove() method retrieves and removes the head of the queue object. If the object is empty, NoSuchElementException is thrown.
This method is similar to the
pollmethod, except thepollmethod doesn’t throwNoSuchElementExceptionif thequeueis empty.
Code
The code below demonstrates how to use the remove() method.
import java.util.concurrent.ConcurrentLinkedQueue;class Remove {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("queue.remove() returns : " + queue.remove());System.out.println("The queue is " + queue);}}
Explanation
-
Line 1: We import the
ConcurrentLinkedQueueclass. -
Line 4: We create a
ConcurrentLinkedQueueobject namedqueue. -
Lines 5 to 7: We use the
add()method of thequeueobject to add three elements ("1","2","3") toqueue. -
Line 10: We use the
remove()method of thequeueobject to retrieve and remove its head. In this case,1is removed and returned.