Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java PriorityQueue offer, poll, and peek Explained

Understand Java's PriorityQueue offer, poll, and peek methods, including how heap ordering determines the head and when to use each method.

~5 min readJava
#PriorityQueue#Java Collections#Heap#Queue API
Diagram showing a Java PriorityQueue with offer adding an element, poll removing the head, and peek viewing the head without removal.

The java.util.PriorityQueue class implements the Queue interface and uses a binary heap to keep the smallest element at the head. Its core queue operations are offer, poll, and peek. This article explains how those methods behave, how ordering is determined, and how to use them correctly in Java applications.

The Core Methods: offer, poll, and peek

PriorityQueue implements the Queue interface and provides three primary methods for interacting with its elements:

  • offer(E e) inserts an element into the queue and returns true if successful.
  • poll() retrieves and removes the head of the queue, or returns null if the queue is empty.
  • peek() retrieves, but does not remove, the head of the queue, or returns null if empty.

The head of a PriorityQueue is the least element according to the queue's ordering. That ordering can be the natural ordering of the elements or a custom ordering provided by a Comparator at construction time.

How PriorityQueue Orders Elements

PriorityQueue is implemented as a binary heap. The head is always the smallest element according to the comparator or natural ordering. This means that offer places an element into the heap and reorders internally to maintain the heap property. poll removes the root and rebalances the heap. peek simply reads the root without any structural changes.

The ordering is determined either by the elements' Comparable implementation or by a Comparator passed to the constructor. For example:

java
PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(5); pq.offer(1); pq.offer(3); System.out.println(pq.peek()); // prints 1

If you need a different ordering, such as max-heap behavior, you can supply a comparator:

java
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); maxHeap.offer(5); maxHeap.offer(1); System.out.println(maxHeap.peek()); // prints 5

offer: Adding an Element

The offer method adds an element to the queue and returns a boolean. The Queue interface defines offer for queues that may reject an element by returning false; add, in contrast, is defined to throw an exception when insertion fails.

PriorityQueue is unbounded, so offer does not return false for capacity reasons. It does reject null: PriorityQueue does not permit null elements, and calling offer(null) throws NullPointerException. For every non-null element, offer returns true.

java
PriorityQueue<String> tasks = new PriorityQueue<>(); boolean added = tasks.offer("process order"); System.out.println(added); // true

Because the queue is unbounded, you do not need to check the return value in normal usage. Checking it is still useful when writing generic queue-handling code that might be swapped with a bounded queue implementation.

poll: Retrieving and Removing the Head

poll returns the head of the queue and removes it. If the queue is empty, it returns null rather than throwing an exception. This makes poll safe to call without checking the queue size first, but you must handle the null return value to avoid NullPointerException when using the result.

java
PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(10); pq.offer(20); Integer first = pq.poll(); // returns 10, queue now contains [20] Integer second = pq.poll(); // returns 20 Integer noElement = pq.poll(); // returns null

After poll removes the head, the heap is restructured to maintain the ordering invariant. This operation has a time complexity of O(log n), where n is the number of elements in the queue.

peek: Inspecting the Head Without Removal

peek returns the head of the queue without removing it. Like poll, it returns null if the queue is empty. This is useful when you need to check the highest-priority element without consuming it, such as in a scheduling loop where you want to decide whether to process the next task.

java
PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(42); Integer head = pq.peek(); // returns 42, queue still contains [42]

Because peek does not modify the heap, it runs in constant time, O(1).

Comparing offer, poll, and peek with add, remove, and element

The Queue interface also defines add, remove, and element. These behave similarly but differ in error handling:

MethodBehavior on failureReturn value
offerThrows NullPointerException for null elements; never returns false for a PriorityQueueboolean
addBehaves like offer for PriorityQueue; bounded Queue implementations may throw IllegalStateExceptionboolean
pollReturns null if emptyE
removeThrows NoSuchElementException if emptyE
peekReturns null if emptyE
elementThrows NoSuchElementException if emptyE

For a PriorityQueue, which is unbounded, add and offer are effectively equivalent for non-null elements. The choice between poll/peek and remove/element depends on whether you want to handle the empty case with a return value or an exception.

Performance Characteristics of PriorityQueue Operations

The underlying heap structure gives offer and poll a time complexity of O(log n). This is because both operations may need to traverse the height of the heap to restore the heap invariant. peek is O(1) because it only reads the root. These costs are important when designing algorithms that repeatedly add or remove elements, such as Dijkstra's shortest path or a priority-based task scheduler.

Memory usage is proportional to the number of elements stored. The queue grows dynamically, so you do not need to pre-size it, but be aware that frequent large insertions may cause reallocation and copying, similar to ArrayList.

PriorityQueue is not thread-safe. If multiple threads access the same instance concurrently, you must synchronize externally or use PriorityBlockingQueue for thread-safe operations.

Practical Example: A Simple Task Scheduler

Consider a scheduler that processes tasks based on priority. Each task has a priority and a description. Using PriorityQueue, you can maintain a list of pending tasks and always process the highest-priority one. This example uses a Java record (Java 16+) to keep the task type small.

java
record Task(int priority, String description) implements Comparable<Task> { @Override public int compareTo(Task other) { return Integer.compare(this.priority, other.priority); } } PriorityQueue<Task> queue = new PriorityQueue<>(); queue.offer(new Task(3, "Send email")); queue.offer(new Task(1, "Fix critical bug")); queue.offer(new Task(2, "Update documentation")); while (!queue.isEmpty()) { Task next = queue.poll(); System.out.println("Processing: " + next.description()); }

This outputs the tasks in order of priority: the critical bug first, then documentation, then email. The offer method adds tasks, poll retrieves and removes the next task, and peek could be used to inspect the next task without removing it if you need to check whether it meets some condition.

Common Pitfalls and Edge Cases

One common mistake is assuming that PriorityQueue maintains a fully sorted order when iterating. The internal heap guarantees only that the head is the smallest; iterating over the queue does not produce elements in sorted order. If you need a sorted traversal, repeatedly call poll or copy the elements into a sorted collection.

Another edge case is tied priorities. If two elements compare as equal under the queue's ordering, the queue does not define which tied element becomes the head. If your application depends on a stable tie-break, encode it in the comparator or in compareTo.

Null elements are not allowed. Attempting to offer a null value throws NullPointerException, so validate inputs before adding them to the queue.

When using a custom object type, ensure that the compareTo method or comparator is implemented correctly. An incorrect ordering can cause the wrong element to be considered the head, which defeats the purpose of a priority queue.

Understanding the exact behavior of offer, poll, and peek allows you to use PriorityQueue effectively in performance-sensitive and correctness-critical applications. Each method has a clear role, and knowing when to use which one avoids common errors and unnecessary overhead.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.