Quick revision
The short answer
The CPU burns because PriorityQueue.remove(job) is a linear scan: with 10 million jobs, every cancellation compares up to 10 million references. We fix it by not searching the heap at all: either mark cancelled jobs and skip them when they reach the top (lazy deletion), keep an indexed heap or a sorted set such as TreeSet or ConcurrentSkipListSet that removes in O(log n), or, for time-based schedules, use a hierarchical timing wheel with O(1) insert and cancel. Jobs that must survive a restart belong in a database, not only in memory.
What to remember
In this answer, we saw that cancellations saturate the CPU because PriorityQueue.remove(Object) is a linear scan, which at 10 million jobs costs millions of comparisons each time. Lazy deletion with occasional compaction makes cancellation O(1) with a small change. An indexed heap or an ordered set such as ConcurrentSkipListSet, keyed by due time and id, gives O(log n) removal. A hierarchical timing wheel gives O(1) insert and cancel for time-based work. And if jobs must survive restarts, the database is the source of truth and memory holds only the near future.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The CPU burns because PriorityQueue.remove(job) is a linear scan: with 10 million jobs, every cancellation compares up to 10 million references. We fix it by not searching the heap at all: either mark cancelled jobs and skip them when they reach the top (lazy deletion), keep an indexed heap or a sorted set such as TreeSet or ConcurrentSkipListSet that removes in O(log n), or, for time-based schedules, use a hierarchical timing wheel with O(1) insert and cancel. Jobs that must survive a restart belong in a database, not only in memory.
Why this question is asked
This is a classic case of a data structure that was correct on day one and wrong at scale. A PriorityQueue ordered by due time is the obvious choice for a scheduler, and with a few thousand jobs nobody notices that cancelling one is expensive. At 10 million jobs and a steady stream of cancellations, the same code saturates the CPU. Interviewers ask this to see whether we can find the real cost from first principles and choose a fix that matches the workload. In this answer, we will confirm why remove(Object) is the problem, then look at four fixes in turn: lazy deletion, an indexed heap, an ordered set, and a timing wheel, and finish with durability and how to choose.
1Why remove(job) Saturates the CPU
A PriorityQueue is a binary heap in an array. It knows that the earliest job is at index 0, but it has no map from a job to its position. So remove(job) walks the array from the start and calls equals() on each element until it finds a match, which is O(n), and only then repairs the heap in O(log n).
With n = 10,000,000, an average cancellation scans about 5 million entries, and a miss scans all 10 million. If users cancel 1,000 jobs per second, that is around 5 billion equals() calls per second, far beyond what one core can do, and since the queue is shared, every scheduling thread waits on the lock around it. A profiler or a few jstack dumps would show threads inside PriorityQueue.indexOf, which confirms the diagnosis before we change anything.
2Fix 1: Lazy Deletion
The cheapest change is to stop removing jobs from the heap at all. Cancelling a job just sets a flag on it, for example a volatile boolean or an AtomicBoolean, or puts its id into a concurrent set. The poller then skips cancelled jobs as they reach the top. Each cancellation becomes O(1), and each cancelled job costs one extra O(log n) poll later, which we were going to pay anyway when the job came due.
But there is a catch: cancelled jobs keep occupying memory until their due time arrives, and a job cancelled today but due next month lingers for a month. If cancellations are a large fraction of the queue, the heap fills with garbage. The usual remedy is to compact occasionally: when cancelledCount exceeds, say, half the size, rebuild the queue from the live jobs, which is O(n) with the collection constructor. ScheduledThreadPoolExecutor has the same trade-off, and its setRemoveOnCancelPolicy(true) switches from lazy deletion to immediate removal.
3Fix 2: An Indexed Heap
If we want real removal, the heap needs to know where each job sits. An indexed heap stores the position of each job, either in a field on the job or in a HashMap from job id to array index, and updates that position every time sifting moves an element. Removal then looks up the index in O(1), moves the last element into the hole, and sifts it up or down in O(log n). The JDK does not ship a public indexed heap, so this is our own code, but it is small. Interestingly, ScheduledThreadPoolExecutor's internal DelayedWorkQueue does exactly this: each task remembers its heapIndex so that removal is fast.
The cost is complexity and memory: every swap must update two positions, and a bug in that bookkeeping silently corrupts the heap. We would test it with a randomised comparison against a simple reference implementation.
4Fix 3: An Ordered Set Keyed by Due Time and Id
A TreeSet, a red-black tree, or a ConcurrentSkipListSet, a lock-free skip list, keeps elements sorted and supports add, remove and pollFirst in O(log n). The comparator must break ties, because two jobs due at the same millisecond are not the same job, and a set would treat them as duplicates and drop one. Comparing by due time and then by id fixes that.
ConcurrentSkipListSet also removes the global lock, so many threads can schedule and cancel concurrently. The price is memory: each element costs several node objects, noticeably more than one array slot in a heap, so 10 million jobs might need a few hundred extra megabytes. We should measure that with a heap dump before committing.
5Fix 4: A Hierarchical Timing Wheel
When jobs are keyed by time, we do not actually need a total order between them. A timing wheel is a circular array of slots, each covering a tick such as one second. A job due in 37 seconds goes into the slot 37 positions ahead of the current one, and cancelling simply unlinks it from that slot's list, so insert and cancel are O(1). A hierarchical wheel adds coarser wheels, minutes, hours, days, for far-off jobs, and moves them down to finer wheels as their time approaches. Netty's HashedWheelTimer and Kafka's purgatory for delayed requests are well-known implementations of this idea.
The trade-off is precision: a job fires on the tick of its slot, not at its exact millisecond, which is fine for a scheduler with second-level granularity.
| Option | Cancel cost | Main cost or risk |
|---|---|---|
PriorityQueue.remove (today) | O(n) | CPU saturation at millions of jobs |
| Lazy deletion | O(1) | dead entries use memory until compaction |
| Indexed heap | O(log n) | custom code, index bookkeeping bugs |
TreeSet / ConcurrentSkipListSet | O(log n) | more memory per element |
| Hierarchical timing wheel | O(1) | tick-level precision, more design work |
6Durability and What I Would Choose
Ten million pending jobs in a single JVM heap is itself a risk: a deployment or a crash loses them all. If the jobs matter, the source of truth should be a database table with a due_at column and an index on (status, due_at), and the in-memory structure becomes a cache of the next window, say the next ten minutes, loaded by a query and refreshed on a timer. Cancellation then updates the row, and the in-memory copy either uses lazy deletion or is reloaded. Libraries such as Quartz with a JDBC store, or db-scheduler, implement this pattern.
For the immediate incident, I would ship lazy deletion with periodic compaction, because it is a ten-line change that turns cancellations into O(1) and can be deployed today. Then I would decide between a skip list and a timing wheel based on how precise firing needs to be, and move durability into the database if jobs must survive restarts.
7Follow-up questions
How often should we compact with lazy deletion?
A simple rule is to rebuild when cancelled entries exceed half of the queue size. Rebuilding is O(n), but it happens only after at least n/2 cancellations, so the amortised cost per cancellation stays O(1). We also monitor the dead-entry count as a metric so we can see whether memory is drifting.
Why not just use a HashMap to find the job and then remove it?
Finding the job is not the slow part on its own; PriorityQueue.remove still scans the array to find the index because the heap does not expose positions. A map only helps if the heap itself uses it to store and update indexes, which is the indexed heap.
Is ConcurrentSkipListSet always better than a locked TreeSet?
Not always. A TreeSet behind one lock is faster for a single thread and uses less memory. The skip list wins when many threads add and remove concurrently, because it avoids one global lock. We would benchmark with JMH using our real thread counts.
8Conclusion
In this answer, we saw that cancellations saturate the CPU because PriorityQueue.remove(Object) is a linear scan, which at 10 million jobs costs millions of comparisons each time. Lazy deletion with occasional compaction makes cancellation O(1) with a small change. An indexed heap or an ordered set such as ConcurrentSkipListSet, keyed by due time and id, gives O(log n) removal. A hierarchical timing wheel gives O(1) insert and cancel for time-based work. And if jobs must survive restarts, the database is the source of truth and memory holds only the near future.
Open with
The root cause is that PriorityQueue.remove of an object is O(n). The heap only knows where the minimum is, so remove scans the array calling equals until it finds the job.
Then, if they want more
With ten million jobs that is millions of comparisons per cancellation, and with a thousand cancellations a second the scheduler threads just spin on that scan. I would confirm it with a profiler or thread dumps showing indexOf.
The quickest fix is lazy deletion: cancel sets a flag, which is O(1), and the poller discards cancelled jobs as they reach the top. To stop dead jobs from filling memory, I rebuild the queue when more than half of it is cancelled, which keeps the amortised cost constant.
If I need true removal, I would use an ordered set like ConcurrentSkipListSet with a comparator on due time and then id, so equal times are not merged, giving log n removal and better concurrency, or an indexed heap that tracks each job's position.
For a scheduler with second-level precision, a hierarchical timing wheel like Netty's or Kafka's gives constant time insert and cancel. Finally, ten million jobs in one JVM is fragile, so if they must survive a restart I would keep them in a database table indexed by due time and only load the next window into memory.
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 official documentation for the version you use. 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 scheduling service holds 10 million pending jobs in a PriorityQueue ordered by due...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/7cf5980a1d/