The remove()
method of the ConcurrentLinkedQueue
class retrieves and removes the ConcurrentLinkedQueue
object.
ConcurrentLinkedQueue
is 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.
public E remove()
This method doesn’t take any arguments.
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
poll
method, except thepoll
method doesn’t throwNoSuchElementException
if thequeue
is empty.
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);}}
Line 1: We import the ConcurrentLinkedQueue
class.
Line 4: We create a ConcurrentLinkedQueue
object named queue
.
Lines 5 to 7: We use the add()
method of the queue
object to add three elements ("1"
,"2"
,"3"
) to queue
.
Line 10: We use the remove()
method of the queue
object to retrieve and remove its head. In this case, 1
is removed and returned.