What is the ConcurrentLinkedQueue.remove(Object o) in Java?
The remove method is used to remove the first occurrence of the specified element in the ConcurrentLinkedQueue object. If the element is not present, then no action is performed.
The
ConcurrentLinkedQueueis a thread-safe unbounded queue. The elements are ordered by. The elements are inserted at the tail (end) and retrieved from the head (start) of the queue. The FIFO First-In-First-Out nullelements are not allowed as an element of the queue. We can use theConcurrentLinkedQueuewhen multiple threads are sharing a single queue.
Syntax
public boolean remove(Object o)
Parameter
This method takes the element to be removed from the queue as a parameter.
Return value
This method returns true if the queue contains the specified element. Otherwise, false is returned.
Code
The below code demonstrates how to use the remove(Object o) 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("1");System.out.println("The queue is " + queue);System.out.println("Is element 1 present & removed: " + queue.remove("1"));System.out.println("The queue is " + queue);System.out.println("\nIs element 4 present & removed: " + queue.remove("4"));System.out.println("The queue is " + queue);}}
Explanation
In the above code:
-
In line 1, we imported the
ConcurrentLinkedQueueclass. -
In line 4, we created a
ConcurrentLinkedQueueobject with the namequeue. -
From line 5 to 7, we used the
add()method of theQueueobject to add three elements ("1","2","3") toqueue. -
On line 10, we used the
remove(Object o)method to remove the first occurrence of the element"1". The element"1"is present in two indexes,0and2. After calling this method, the element at index0will be removed andtruewill be returned. -
On line 13, we used the
remove(Object o)method to remove the first occurrence of the element"4". The element"4"is not present. So,queueremains unchanged and this method returnsfalse.