Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

peek
arrayblockingqueue
java
communitycreator

What is the ArrayBlockingQueue.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.

ArrayBlockingQueue is a bounded queue and it is thread-safe. Internally, it uses a fixed-size array. Once the object is created, the size cannot be changed. The elements of this queue follow First-In-First-OutElements are inserted at the end of the queue and retrieved from the head of the queue.. Also, null objects are not allowed as elements.

The peek method can be used to get the head element (first element) of the ArrayBlockingQueue object.

Syntax

public E peek()

Parameters

This method doesn’t take any argument.

Return value

This method returns the head element of the queue. If the queue is empty, then null is returned.

Code

The code below demonstrates how to use the peek method.

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

Explanation

In the above code:

  • We imported the ArrayBlockingQueue from the java.util.concurrent package.

  • We created an object for the ArrayBlockingQueue class with the name queue and size 5.

  • We used the add method to add three elements to the queue object.

  • We used the peek method to get the head element of the queue.

RELATED TAGS

peek
arrayblockingqueue
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