Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
}
}
Example of the ConcurrentLinkedQueue.add() method

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring