Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

element
java
communitycreator

What is the ConcurrentLinkedQueue.element() 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.

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

The element method can be used to get the head of the ConcurrentLinkedQueue object.

Syntax

public E element()

Parameters

This method doesn’t take in any parameters.

Return value

This method retrieves the head of the queue. If the queue is empty, then a NoSuchElementException is thrown.

This method is similar to the peek method, except that the element method throws the NoSuchElementException if the queue is empty, whereas the peek method returns null.

Code

The code below demonstrates how to use the element method.

import java.util.concurrent.ConcurrentLinkedQueue;
class Element {
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.element() returns : " + queue.element());
}
}

Explanation

In the code above:

  • In line 1, we import the ConcurrentLinkedQueue class.

  • In line 4, we create a ConcurrentLinkedQueue object with the name queue.

  • In lines 5 to 7, we use the add() method of the queue object to add three elements (1, 2, 3) to queue.

  • In line 10, we use the element() method of the queue object to get the head. In our case, 1 will be returned.

RELATED TAGS

element
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