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

Overview

ConcurrentLinkedQueue is a thread-safe, unbounded queue. The elements are ordered by FIFO (First-In-First-Out). They are inserted at the tail (end) and retrieved from the head (start) of the queue. null elements are not allowed to be part of the queue. We can use the ConcurrentLinkedQueue when multiple threads share a single queue.

The ConcurrentLinkedQueue.add method can be used to insert an element to the end (tail) of the queue.

Syntax

public boolean add(E e)

Parameters

This method takes the element to be added to the queue as an argument.

Here, E is the datatype of the elements held in the queue.

Return value

The add method returns true if the element is successfully added to the queue.

Code

The code below demonstrates how to use the add method.

import java.util.concurrent.ConcurrentLinkedQueue;
class Add {
public static void main( String args[] ) {
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
queue.add("1");
queue.add("2");
queue.add("3");
queue.add("4");
queue.add("5");
System.out.println("The queue is " + queue);
}
}

Explanation

  • In line 1, we import the ConcurrentLinkedQueue from the java.util.concurrent package.

  • In line 4, we create an object for the ConcurrentLinkedQueue class with the name queue.

  • In lines 5-9, we use the add method to add five elements to the queue object and print it.

Free Resources