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
ConcurrentLinkedQueue
is 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 null
elements are not allowed as an element of the queue. We can use theConcurrentLinkedQueue
when multiple threads are sharing a single queue.
public boolean remove(Object o)
This method takes the element to be removed from the queue
as a parameter.
This method returns true
if the queue
contains the specified element. Otherwise, false
is returned.
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);}}
In the above code:
In line 1, we imported the ConcurrentLinkedQueue
class.
In line 4, we created a ConcurrentLinkedQueue
object with the name queue
.
From line 5 to 7, we used the add()
method of the Queue
object to add three elements ("1"
,"2"
,"3"
) to queue
.
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, 0
and 2
. After calling this method, the element at index 0
will be removed and true
will 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, queue
remains unchanged and this method returns false
.