Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

The peek() method of the ConcurrentLinkedQueue class can be used to get the head (first element) of a queue.

Note: 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. We can use the ConcurrentLinkedQueue when multiple threads share a single queue.

Syntax

public E peek()

Return value

This method returns the head element of the queue.

If the ConcurrentLinkedQueue is empty, the method returns null.

Example

The code below demonstrates how to use the peek() method.

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

Explanation

In the code above:

  • Line 1: We import the ConcurrentLinkedQueue class.

  • Line 4: We create a ConcurrentLinkedQueue object with the name 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 peek() method of the queue object to get the head of queue. In our case, the return value is 1.

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