What is the ConcurrentLinkedQueue.remove() method in Java?

Overview

The remove() method of the ConcurrentLinkedQueue class retrieves and removes the headThe first element of 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.

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 poll method, except the poll method doesn’t throw NoSuchElementException if the queue is 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 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.

Free Resources