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.

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 returnstrueif successful.poll()retrieves and removes the head of the queue, or returnsnullif the queue is empty.peek()retrieves, but does not remove, the head of the queue, or returnsnullif 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:
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(1);
pq.offer(3);
System.out.println(pq.peek()); // prints 1If you need a different ordering, such as max-heap behavior, you can supply a comparator:
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
maxHeap.offer(5);
maxHeap.offer(1);
System.out.println(maxHeap.peek()); // prints 5offer: 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.
PriorityQueue<String> tasks = new PriorityQueue<>();
boolean added = tasks.offer("process order");
System.out.println(added); // trueBecause 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.
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 nullAfter 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.
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:
| Method | Behavior on failure | Return value |
|---|---|---|
offer | Throws NullPointerException for null elements; never returns false for a PriorityQueue | boolean |
add | Behaves like offer for PriorityQueue; bounded Queue implementations may throw IllegalStateException | boolean |
poll | Returns null if empty | E |
remove | Throws NoSuchElementException if empty | E |
peek | Returns null if empty | E |
element | Throws NoSuchElementException if empty | E |
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.
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 toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.