Scrivio Interview library
DebuggingIntermediate8 min read · updated 12 November 2026

A job scheduler stores Job objects in a PriorityQueue ordered by job.priority. An admin endpoint changes job.priority for queued jobs. Afterwards jobs run in an order that matches neither the old nor the new priorities. Explain and fix.

PriorityQueue only restores its heap order when elements are added or removed, so changing job.priority on a job that is already in the queue leaves it in a position chosen for the old value. Later polls follow that stale structure and produce an order that matches neither the old nor the new priorities. The fix is to remove the job, change its priority and add it back, or to treat queue entries as immutable and use lazy deletion, and to guard the queue if more than one thread touches it.

Why this question is asked

This bug appears in schedulers, rate limiters and game loops: something in a priority queue changes its priority, and the queue quietly starts returning things in a strange order. No exception is thrown, and the order is not even the old one, which makes it hard to reason about. Interviewers ask it because the answer requires knowing what invariant a heap maintains and when it maintains it. In this answer, we will recap the heap invariant, reproduce the bug with five jobs, trace exactly why the output is scrambled, and then look at two fixes and the concurrency issue that usually comes with this code.

1A Quick Recap of the Heap Invariant

PriorityQueue keeps its elements in an array arranged as a binary min-heap. The invariant, the rule that must always hold, is that every parent compares smaller than or equal to its children according to the comparator. The queue relies on that rule completely: poll simply takes the element at index 0, and then sifts the last element down from the root, comparing it only with the children along one path.

The queue enforces the invariant at two moments only: when an element is inserted (sift up) and when one is removed (sift down). The comparator is called at those moments. If a field that the comparator reads changes while the element sits in the array, the queue does not know, because nothing calls into it. The array now violates the rule, and every later operation makes decisions based on comparisons that assume it still holds.

2Reproducing the Bug

Here is a small scheduler where a lower number means more urgent. Five jobs are queued with priorities 1 to 5. Then an admin endpoint changes job a to 9 (least urgent) and job d to 0 (most urgent).

Java
class Job {
final String name; int priority; // mutable, read by the comparator
Job(String name, int priority) { this.name = name; this.priority = priority; }
}
PriorityQueue<Job> queue = new PriorityQueue<>(Comparator.comparingInt((Job j) -> j.priority));
Job a = new Job("a", 1), b = new Job("b", 2), c = new Job("c", 3), d = new Job("d", 4), e = new Job("e", 5);
List.of(a, b, c, d, e).forEach(queue::offer); // array: [a1, b2, c3, d4, e5]
a.priority = 9; // admin endpoint
d.priority = 0; // admin endpoint, array now [a9, b2, c3, d0, e5]
while (!queue.isEmpty()) System.out.print(queue.poll().name + " ");
// a b d c e

The old order would have been a b c d e. The intended new order is d b c e a. The queue produces a b d c e, which matches neither. Job a, now the least urgent, runs first, and job d, now the most urgent, runs third.

3Tracing Why the Order Is Scrambled

The first poll returns whatever sits at index 0, which is a. The queue does not compare anything to choose it; the invariant says the root is the minimum, so it trusts that. Then it moves the last element, e5, to the root and sifts it down: the smaller child of the root is b2, so e5 swaps with b2; then at index 1 its only child is d0, which is smaller, so they swap. The array becomes [b2, d0, c3, e5].

The second poll returns b from the root. e5 moves up and sifts down past d0, giving [d0, e5, c3]. The third poll returns d, the fourth c, the fifth e. Notice that d only reached the root because sifting happened to compare it on the way; c3 was never compared with d at all until both were near the top. The result depends on where each job was placed under the old priorities and which comparisons the later sift operations happen to make.

The queue array after each poll
PollReturnedArray afterwardsWhy
1a (priority 9)[b2, d0, c3, e5]root is trusted; e5 sifts down past b2 and d0
2b (priority 2)[d0, e5, c3]e5 sifts down past d0
3d (priority 0)[c3, e5]c3 is the last element, moves up, no swap
4c (priority 3)[e5]
5e (priority 5)[]
Poll 1 returns the least urgent job because the root was never re-checked.

4Fix 1: Remove, Change, Re-Add

The direct fix is to take the job out before changing the field and put it back afterwards. remove reorganizes the heap without the job, and offer inserts it at the correct place for its new priority, so the invariant holds again.

Java
synchronized void changePriority(Job job, int newPriority) {
if (queue.remove(job)) { // O(n): scans the array, then repairs the heap
job.priority = newPriority;
queue.offer(job); // O(log n): sifts into the right place
} else {
job.priority = newPriority; // not queued (running or done): just update
}
}
// with this, the same admin changes give: d b c e a

The cost is that remove(Object) scans the array with equals, so it is O(n). For a queue of a few thousand jobs and occasional admin changes, that is completely fine. Note that remove uses equals, so if Job overrides equals by name, a different object with the same name would match; that is usually what we want, but worth knowing.

5Fix 2: Immutable Entries and Lazy Deletion

If priorities change often or the queue is large, a better design never mutates anything inside the queue. Each queue entry is an immutable snapshot: the job, the priority at the time, and a version number. Changing a priority increments the job's version and adds a new entry. When the scheduler polls, it skips entries whose version no longer matches the job's current version.

Java
// Job now also has: final AtomicLong version = new AtomicLong();
record Entry(int priority, long version, Job job) {}
PriorityQueue<Entry> queue = new PriorityQueue<>(Comparator.comparingInt(Entry::priority));
void changePriority(Job job, int newPriority) {
long v = job.version.incrementAndGet(); // old entries become stale
job.priority = newPriority;
queue.offer(new Entry(newPriority, v, job)); // O(log n), no scan
}
Job next() {
Entry e;
while ((e = queue.poll()) != null) {
if (e.version() == e.job().version.get()) return e.job(); // current entry
// stale entry: skip it
}
return null;
}

Every operation is now O(log n). The cost is memory: stale entries stay in the heap until they reach the root. If priorities change very frequently, we track the number of stale entries and rebuild the queue from the live jobs when they exceed, say, half of the size. Cancellation works the same way: bump the version, and the entry is skipped when it surfaces.

6When Several Threads Share the Queue

In this scenario an admin endpoint runs on a web request thread while the scheduler polls on its own thread. PriorityQueue is not thread-safe, so even the correct remove-and-re-add can corrupt the array if it overlaps with a poll. We either guard every access with the same lock, as the synchronized method above suggests, or switch to PriorityBlockingQueue, whose operations are each protected by an internal lock.

But PriorityBlockingQueue does not solve the mutation problem: changing the field still bypasses the heap, and remove followed by offer is two separate operations, so another thread can poll in between. The lazy deletion design fits concurrent use best, because a priority change is a single offer, and with PriorityBlockingQueue the scheduler can block on take while waiting for work.

7Follow-up questions

Could we call some method to re-heapify after changing the field?

PriorityQueue has no public method for that. The closest is building a new PriorityQueue from the old one's contents, which heapifies in O(n). That works for rare bulk changes, but rebuilding on every update is more expensive than remove and re-add.

Does the same problem affect TreeSet and TreeMap?

Yes, and it is worse. A TreeSet places elements by comparison at insertion; if the fields used by the comparator change, lookups and removals walk the wrong branch, so contains and remove may fail to find the element at all. The rule is general: never mutate a field that a sorted or hashed collection uses to place an element while it is inside the collection.

How would you make this mistake impossible?

Make the fields the comparator uses immutable, for example by using a record for queue entries as in the lazy deletion design. Then the only way to change priority is to create a new entry and offer it, which always goes through the heap.

8Conclusion

In this answer, we saw that PriorityQueue maintains its heap invariant only when elements are inserted or removed, so mutating job.priority for a queued job leaves a heap whose shape reflects the old values. poll trusts the root and sifts along single paths, so the output follows the stale structure and matches neither priority order. We fixed it by removing, changing and re-adding the job at O(n) per change, or with immutable entries and lazy deletion at O(log n), and we guarded the queue because the admin endpoint and the scheduler run on different threads.

What to say in the interviewAbout 100 seconds aloud

Open with

A PriorityQueue is a binary heap in an array, and it only enforces the heap rule, parent smaller than children, when an element is offered or polled. The comparator reads job.priority, so when the admin endpoint changes that field on a queued job, nothing tells the queue.

Then, if they want more

The job stays where its old priority put it, and poll simply trusts that the root is the minimum, then sifts the last element down along one path, comparing only a few elements. So later polls follow the stale structure, and the order matches neither the old nor the new priorities.

For example, a job demoted from first to last still sits at the root and runs next. The simplest fix is to remove the job, change the priority and offer it again, so it is inserted at the right place. remove of an object is O(n) because it scans the array, which is fine for occasional admin changes.

If changes are frequent or the queue is large, I prefer immutable entries with lazy deletion: each entry holds the priority and a version; a change bumps the job's version and offers a new entry, and the scheduler skips entries whose version is outdated when it polls them.

That keeps everything O(log n), and we rebuild if stale entries pile up. Since the admin endpoint and scheduler are different threads, I would also guard the queue with a lock or use PriorityBlockingQueue, keeping in mind that it does not fix mutation by itself.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A job scheduler stores Job objects in a PriorityQueue ordered by job.priority. An admin...": https://scrivio-interview-library.netlify.app/java/queues-and-deques/37909ab441/