PriorityQueue
A PriorityQueue always hands out its smallest element first, by natural order or a comparator, without keeping everything sorted. It does this with a binary heap stored in an array. This page explains how the heap works, shows why printing the queue looks unsorted, builds a scheduler and a top-K selection, covers the traps, and measures a heap against sorting.
Contents
How a PriorityQueue works: a binary heap Heap order versus poll order Inside the heap, and its rules A task scheduler with tie-breakers Top K with a small heap A heap versus sorting Two classic heap algorithms: k-way merge and running median Thread-safe and delayed priority queues When to use a PriorityQueue
How a PriorityQueue works: a binary heap
PriorityQueue
oroffer places the new element at the end and swaps it upward while it is smaller than its parent: O(log n).add removes the root, moves the last element to the top and swaps it downward: O(log n).poll reads the root: O(1).peek andremove(Object) search the array linearly: O(n).contains
Because only the root is guaranteed, iterating or printing a priority queue does not show its elements in priority order. Only repeated poll
| Method | Cost | On an empty queue |
|---|---|---|
offer(e)add(e) | O(log n) | Not applicable; null |
poll() | O(log n) | Returns null |
remove() | O(log n) | Throws NoSuchElementException |
peek() | O(1) | Returns null |
element() | O(1) | Throws NoSuchElementException |
remove(o)contains(o) | O(n) | Returns false |
Iteration, toString | O(n) | Array order, not priority order |
For a thread-safe version, PriorityBlockingQueuetake()
Heap order versus poll order
Six unsorted numbers go in; the program prints the queue, peeks, and then polls until it is empty.
import java.util.PriorityQueue;
public class HeapOrder {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int n : new int[] {42, 7, 19, 3, 25, 11}) {
pq.offer(n);
}
// printing or iterating shows the internal heap array, NOT sorted order
System.out.println("toString: " + pq);
System.out.println("peek: " + pq.peek() + " (smallest, not removed)");
// poll always removes the current smallest
StringBuilder order = new StringBuilder();
while (!pq.isEmpty()) {
order.append(pq.poll()).append(' ');
}
System.out.println("poll order: " + order.toString().trim());
System.out.println("poll on empty: " + pq.poll());
}
}
Output:
toString: [3, 7, 11, 42, 25, 19]
peek: 3 (smallest, not removed)
poll order: 3 7 11 19 25 42
poll on empty: null
showedtoString , the heap array. The smallest, 3, is first, but 42 comes before 25 and 19.[3, 7, 11, 42, 25, 19] returned 3 without removing it.peek- Polling returned the numbers in ascending order, 3 to 42, because each
restores the heap rule before the next one.poll on an empty queue returnedpoll , so anull loop is a common way to drain it.while ((x = pq.poll()) != null)
Inside the heap, and its rules
The same numbers are added one at a time, printing the array after each step. The rest of the program shows a max-heap and the two mistakes that break a priority queue.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class HeapRules {
static final class Task {
String name;
int priority;
Task(String name, int priority) {
this.name = name;
this.priority = priority;
}
@Override
public String toString() {
return name + ":" + priority;
}
}
public static void main(String[] args) {
// The array layout: children of index i are at 2i+1 and 2i+2
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int x : new int[] {42, 7, 19, 3, 25, 11}) {
pq.add(x);
System.out.println("add " + x + " -> array " + pq);
}
// Iteration and toString follow the array, not priority order
List<Integer> iterated = new ArrayList<>(pq);
System.out.println("iterator order: " + iterated + ", sorted? "
+ iterated.equals(iterated.stream().sorted().toList()));
// Max-heap with a reversed comparator
PriorityQueue<Integer> max = new PriorityQueue<>(Comparator.reverseOrder());
max.addAll(List.of(42, 7, 19, 3));
System.out.println("max-heap poll: " + max.poll() + " " + max.poll());
// Changing a priority after insertion breaks the heap
Task a = new Task("a", 5);
Task b = new Task("b", 3);
Task c = new Task("c", 8);
PriorityQueue<Task> tasks = new PriorityQueue<>(Comparator.comparingInt(t -> t.priority));
tasks.addAll(List.of(a, b, c));
c.priority = 1; // c should now come first...
System.out.println("after changing c to 1, poll() = " + tasks.poll() + " (wrong)");
// The fix: remove, change, re-add
tasks.remove(c);
c.priority = 1;
tasks.add(c);
System.out.println("after remove/re-add, poll() = " + tasks.poll());
// Comparable required without a comparator
PriorityQueue<Object> bad = new PriorityQueue<>();
try {
bad.add(new Object());
} catch (ClassCastException e) {
System.out.println("add a non-Comparable: ClassCastException");
}
}
}
Output:
add 42 -> array [42]
add 7 -> array [7, 42]
add 19 -> array [7, 42, 19]
add 3 -> array [3, 7, 19, 42]
add 25 -> array [3, 7, 19, 42, 25]
add 11 -> array [3, 7, 11, 42, 25, 19]
iterator order: [3, 7, 11, 42, 25, 19], sorted? false
max-heap poll: 42 19
after changing c to 1, poll() = b:3 (wrong)
after remove/re-add, poll() = c:1
add a non-Comparable: ClassCastException
- Adding 7 after 42 swapped it to the front. Adding 3 put it at index 3, then swapped it past 7 at index 1 and to the root. Each add moved the new element up at most two levels.
- The iterator returns the array as it is, which is not sorted. To list elements in priority order without draining the queue, copy it and poll the copy, or sort a copy of its contents.
turns it into a max-heap, which returned 42 and then 19.Comparator.reverseOrder()- The heap places an element when it is added. Changing a task's priority from 8 to 1 afterwards did not move it, so
returnedpoll . Remove the element, change it and add it again, or use immutable elements.b - Without a comparator, elements must be
; adding anComparable threwObject .ClassCastException
A task scheduler with tie-breakers
Tasks have a priority, where 5 is most urgent, and a creation time. Two pairs share a priority, so the queue needs a rule for ties.
import java.util.Comparator;
import java.util.PriorityQueue;
public class Scheduling {
record Task(String name, int priority, long createdAt) {
}
public static void main(String[] args) {
// Highest priority first; among equals, the oldest first
PriorityQueue<Task> queue = new PriorityQueue<>(
Comparator.comparingInt(Task::priority).reversed()
.thenComparingLong(Task::createdAt));
queue.add(new Task("send newsletter", 1, 100));
queue.add(new Task("fix outage", 5, 105));
queue.add(new Task("reply to customer", 3, 101));
queue.add(new Task("rotate keys", 5, 102));
queue.add(new Task("update docs", 1, 99));
while (!queue.isEmpty()) {
Task t = queue.poll();
System.out.println("p" + t.priority() + " t=" + t.createdAt() + " " + t.name());
}
}
}
Output:
p5 t=102 rotate keys
p5 t=105 fix outage
p3 t=101 reply to customer
p1 t=99 update docs
p1 t=100 send newsletter
- The comparator orders by priority, highest first, and then by creation time, oldest first, so equally urgent tasks come out in the order they arrived.
is not stable: without the time tie-breaker, the order of equal-priority tasks would be arbitrary. A sequence number or timestamp in the comparator restores first-come, first-served behaviour.PriorityQueue- Scheduled executors and event simulations are built on this structure;
uses a heap ordered by the time each task is due.ScheduledThreadPoolExecutor
Top K with a small heap
Finding the k largest values does not require sorting everything. The program keeps a min-heap of at most k elements and drops the smallest whenever it grows past k.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
public class TopK {
// Keep the k largest values seen so far in a MIN-heap of size k
static List<Integer> topK(int[] values, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int v : values) {
heap.offer(v);
if (heap.size() > k) {
heap.poll(); // drop the smallest of the k + 1
}
}
List<Integer> result = new ArrayList<>(heap);
result.sort(Collections.reverseOrder());
return result;
}
public static void main(String[] args) {
int[] small = {5, 1, 9, 3, 7, 9, 2};
System.out.println("top 3 of small: " + topK(small, 3));
int[] big = new Random(1).ints(1000000, 0, 1000000000).toArray();
long start = System.nanoTime();
List<Integer> top = topK(big, 5);
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("top 5 of 1,000,000: " + top + " in " + ms + " ms");
}
}
Output (the time is a single run):
top 3 of small: [9, 9, 7]
top 5 of 1,000,000: [999999209, 999998869, 999998609, 999997479, 999996893] in 30 ms
- The heap's root is the smallest of the current top k, so each new value only has to be compared with it. Larger values replace it; smaller ones are dropped.
- The work is O(n log k) and the memory O(k), so the top 5 of a million values needed a heap of only 6 elements at a time.
- Polling the heap at the end gives the top k in ascending order; the program reverses them for display.
A heap versus sorting
To quantify the top-K advantage, the program finds the 10 largest of a million random integers three ways, keeping the fastest of three runs.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.function.Supplier;
public class HeapSpeed {
public static void main(String[] args) {
int[] data = new Random(1).ints(1000000, 0, 1000000000).toArray();
System.out.println("top 10 of 1,000,000 random ints");
time("sort everything, take 10", () -> {
List<Integer> all = new ArrayList<>(data.length);
for (int x : data) {
all.add(x);
}
all.sort(Collections.reverseOrder());
return all.subList(0, 10).get(9);
});
time("min-heap of size 10", () -> {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int x : data) {
if (heap.size() < 10) {
heap.add(x);
} else if (x > heap.peek()) {
heap.poll();
heap.add(x);
}
}
return heap.peek();
});
time("stream sorted().limit(10)", () -> java.util.Arrays.stream(data).boxed()
.sorted(Collections.reverseOrder()).limit(10).toList().get(9));
}
// Best of 3 runs
static void time(String name, Supplier<Integer> f) {
long best = Long.MAX_VALUE;
int tenth = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
tenth = f.get();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-28s %7.1f ms (10th largest %,d)%n", name, best / 1e6, tenth);
}
}
Output (approximate times; 2-CPU Linux machine, JDK 21):
top 10 of 1,000,000 random ints
sort everything, take 10 284.3 ms (10th largest 999,994,899)
min-heap of size 10 3.0 ms (10th largest 999,994,899)
stream sorted().limit(10) 280.8 ms (10th largest 999,994,899)
- Boxing and sorting all million values took hundreds of milliseconds, and so did a stream with
, which also sorts everything before limiting.sorted().limit(10) - The size-10 heap was dozens of times faster in every run on this machine. Most values were smaller than the heap's root and were rejected with a single comparison.
- For k close to n, sorting is as good. The heap wins when k is small compared with n, or when values arrive one at a time and the full set is never stored.
Two classic heap algorithms: k-way merge and running median
Many algorithms need "the smallest of several candidates" over and over, which is exactly what a heap provides. The program merges four already sorted lists, one of them empty, into one sorted list, and keeps the median of a stream of numbers up to date as each number arrives.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
public class HeapAlgorithms {
// k-way merge: always take the smallest head among k sorted lists
static List<Integer> merge(List<List<Integer>> lists) {
record Head(int value, int list, int index) { }
PriorityQueue<Head> heads = new PriorityQueue<>(
(a, b) -> Integer.compare(a.value, b.value));
for (int i = 0; i < lists.size(); i++) {
if (!lists.get(i).isEmpty()) {
heads.add(new Head(lists.get(i).get(0), i, 0));
}
}
List<Integer> out = new ArrayList<>();
while (!heads.isEmpty()) {
Head h = heads.poll();
out.add(h.value);
int next = h.index + 1;
if (next < lists.get(h.list).size()) {
heads.add(new Head(lists.get(h.list).get(next), h.list, next));
}
}
return out;
}
// Running median: a max-heap for the lower half, a min-heap for the upper half
static final PriorityQueue<Integer> LOWER = new PriorityQueue<>(Collections.reverseOrder());
static final PriorityQueue<Integer> UPPER = new PriorityQueue<>();
static double addAndMedian(int x) {
if (LOWER.isEmpty() || x <= LOWER.peek()) {
LOWER.add(x);
} else {
UPPER.add(x);
}
if (LOWER.size() > UPPER.size() + 1) { // rebalance so sizes differ by at most 1
UPPER.add(LOWER.poll());
} else if (UPPER.size() > LOWER.size()) {
LOWER.add(UPPER.poll());
}
return LOWER.size() > UPPER.size() ? LOWER.peek() : (LOWER.peek() + UPPER.peek()) / 2.0;
}
public static void main(String[] args) {
List<List<Integer>> sorted = List.of(List.of(1, 4, 9), List.of(2, 3, 10, 12),
List.of(), List.of(5, 6));
System.out.println("merged: " + merge(sorted));
StringBuilder sb = new StringBuilder();
for (int x : new int[] {5, 15, 1, 3, 8, 7, 9, 10}) {
sb.append(x).append("->").append(addAndMedian(x)).append(" ");
}
System.out.println("running median: " + sb.toString().strip());
}
}
Output:
merged: [1, 2, 3, 4, 5, 6, 9, 10, 12]
running median: 5->5.0 15->10.0 1->5.0 3->4.0 8->5.0 7->6.0 9->7.0 10->7.5
- k-way merge: the heap holds only the current head of each list, at most k elements. Each step takes the smallest head and pushes the next element of the same list, so merging n elements from k lists costs O(n log k) and needs O(k) extra memory. This is how databases and
utilities merge sorted runs that are too big to sort in memory together. The empty list was simply never added.sort - Running median: a max-heap holds the lower half of the numbers and a min-heap the upper half, kept within one element of each other in size. The median is then the top of the larger heap, or the average of both tops. After 5 and 15 the median was 10.0; after adding 1 it was 5.0. Each new number costs O(log n), where re-sorting every time would cost O(n log n).
- A max-heap is just a
withPriorityQueue . The recordCollections.reverseOrder() remembers which list each value came from, so the next element can be found.Head
Thread-safe and delayed priority queues
PriorityQueuejava.util.concurrentPriorityBlockingQueueDelayQueuePriorityBlockingQueue
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
public class DelayedAndBlocking {
// An element that becomes available only after its delay has passed
record Retry(String job, long dueNanos) implements Delayed {
static Retry in(String job, long millis) {
return new Retry(job, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis));
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(dueNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(Delayed other) {
return Long.compare(getDelay(TimeUnit.NANOSECONDS),
other.getDelay(TimeUnit.NANOSECONDS));
}
}
public static void main(String[] args) throws InterruptedException {
DelayQueue<Retry> retries = new DelayQueue<>();
long start = System.nanoTime();
retries.add(Retry.in("send email", 300));
retries.add(Retry.in("call webhook", 100));
retries.add(Retry.in("resize image", 200));
System.out.println("poll() right away: " + retries.poll() + " (nothing is due yet)");
for (int i = 0; i < 3; i++) {
Retry r = retries.take(); // waits until the next one is due
long waited = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
System.out.printf("took %-13s after ~%d ms%n", r.job(), waited / 100 * 100);
}
// PriorityBlockingQueue: thread-safe, and take() waits for an element
PriorityBlockingQueue<Integer> pbq = new PriorityBlockingQueue<>();
Thread producer = Thread.ofPlatform().start(() -> {
try {
Thread.sleep(150);
pbq.add(42);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.println("PriorityBlockingQueue.take() waited and got " + pbq.take());
producer.join();
}
}
Output:
poll() right away: null (nothing is due yet)
took call webhook after ~100 ms
took resize image after ~200 ms
took send email after ~300 ms
PriorityBlockingQueue.take() waited and got 42
right after adding returnedpoll() : anull only hands out elements whose delay has expired, even though it holds three.DelayQueue waited for each one and returned them by due time, not insertion order: the webhook after about 100 ms, then the image, then the email. Elements implementtake() , withDelayed reporting the time left andgetDelay ordering by it. This is a simple building block for retries and timeouts;compareTo uses a similar delayed queue internally.ScheduledThreadPoolExecutor blocked until the producer thread added 42 about 150 ms later. The queue is unbounded, soPriorityBlockingQueue.take() never blocks; to limit memory, bound it yourself, for example with aput . Its iterator, likeSemaphore 's, does not return elements in priority order.PriorityQueue
When to use a PriorityQueue
| Need | Use |
|---|---|
| Always process the smallest or most urgent next | PriorityQueue |
| Largest first | new PriorityQueue<>(Comparator.reverseOrder()) |
| Fair order among equal priorities | A sequence number or timestamp as tie-breaker |
| Top k of many values | A min-heap of size k |
| All elements in sorted order once | Sort a list instead |
| Sorted iteration and lookups | TreeSetTreeMap |
| Priorities that change | Remove and re-add, or a TreeSet |
| Producers and consumers on different threads | PriorityBlockingQueue |
Other queue types are compared on the