Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A service has one shared pool for request work and a periodic cleanup job. Under steady high load, the cleanup task submitted to the pool runs hours late and memory grows. Diagnose and fix.

The cleanup task is starved: it is submitted to the same pool as request work, and under steady high load the pool's queue is always full of request tasks, so the cleanup waits behind hours of backlog while the garbage it should remove keeps piling up. We fix it by running periodic maintenance on its own scheduled executor, bounding the request queue so the backlog cannot grow without limit, tracking the time since the last cleanup as a metric, and making cleanup incremental so each run is short.

Why this question is asked

Background jobs that share resources with request handling usually work fine until the day traffic stays high for hours. Then the job silently stops running, memory grows, and the first alert is often an out-of-memory error, far from the real cause. Interviewers like this scenario because it combines two problems, starvation and an unbounded queue, and the fix needs both isolation and observability. In this answer, we will recap how a shared executor orders work, diagnose the starvation, and then go through the four fixes and why each is needed.

1A Quick Recap of a Shared Executor

A ThreadPoolExecutor runs tasks on a fixed set of worker threads and keeps waiting tasks in a queue. Executors.newFixedThreadPool(n) uses a LinkedBlockingQueue with no capacity limit, and tasks are taken from it in submission order. So a task submitted now runs only after every task already in the queue has started.

A periodic cleanup job is often implemented by a timer that submits a cleanup task to whatever executor is handy, the same one request work uses.

Java
ExecutorService shared = Executors.newFixedThreadPool(32); // unbounded queue
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(() -> shared.submit(this::cleanupExpiredSessions), 5, 5, TimeUnit.MINUTES);
// request handling: shared.submit(() -> handle(request)); thousands per second

2Diagnosing the Starvation

Under steady high load, request tasks arrive faster than 32 workers can finish them, or at least as fast. The queue never drains, and it grows. When the timer submits the cleanup task, it joins the back of that queue. If the queue holds 2 million request tasks and the pool completes 500 per second, the cleanup waits about 2,000,000 / 500 = 4,000 seconds, more than an hour, before it even starts. Meanwhile the timer keeps adding more cleanup tasks behind it.

Memory grows for two reasons at once: the expired sessions the cleanup should remove keep accumulating, and the unbounded queue itself holds millions of pending request tasks, each with its request data. The thread dump looks completely normal, with all 32 workers busy handling requests, which is why this is easy to misread as a memory leak.

Step throughWhy the cleanup runs hours late
  1. Timer fires every 5 minutessubmits cleanup to the shared pool
  2. Queue already holds 2 million request taskssteady high load keeps it full
  3. Cleanup waits for every task ahead of it2,000,000 / 500 per second = about 67 minutes
  4. Expired sessions keep accumulatingmemory grows
  5. Queue keeps growing toounbounded LinkedBlockingQueue

5 steps in order. Play them, or step through them one at a time.

3Fix 1: Give Maintenance Its Own Scheduled Executor

Periodic maintenance should never compete with request work for the same queue. A dedicated ScheduledExecutorService, even with a single thread, runs the cleanup at its scheduled time regardless of how busy the request pool is.

Java
ScheduledExecutorService maintenance = Executors.newSingleThreadScheduledExecutor(
Thread.ofPlatform().name("maintenance").factory());
maintenance.scheduleWithFixedDelay(this::cleanupExpiredSessions, 5, 5, TimeUnit.MINUTES);
// runs 5 minutes after the previous run finished, independently of the request pool

Notice the use of scheduleWithFixedDelay instead of scheduleAtFixedRate: if one run takes longer than expected, the next one starts 5 minutes after it ends rather than piling up. In Spring, a @Scheduled method runs on the task scheduler, which is separate from request threads by default; the bug usually comes from code that submits scheduled work to a shared application executor.

4Fix 2: Bound the Request Queue

Isolation fixes the cleanup, but the unbounded queue is a problem of its own. A queue that can grow to millions of tasks only turns overload into latency and memory use; requests that wait an hour are useless anyway, because their clients gave up long ago. Bounding the queue makes overload visible and lets the service reject work it cannot do in time.

Java
ThreadPoolExecutor requests = new ThreadPoolExecutor(
32, 32, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(2_000), // at most 2,000 waiting tasks
new ThreadPoolExecutor.AbortPolicy()); // full queue -> RejectedExecutionException
// the caller maps the rejection to HTTP 503, so clients back off or retry elsewhere

The size comes from the latency we can accept: with 500 completions per second, a queue of 2,000 means at most about 4 seconds of waiting. Anything beyond that is rejected quickly instead of waiting long enough to be pointless.

5Fix 3: Measure the Time Since the Last Cleanup

This bug went unnoticed because nothing measured whether the cleanup ran. The fix is a gauge that reports how long ago the last successful run finished, with an alert when it exceeds a few intervals.

Java
private final AtomicLong lastCleanup = new AtomicLong(System.currentTimeMillis());
Gauge.builder("sessions.cleanup.age.seconds",
() -> (System.currentTimeMillis() - lastCleanup.get()) / 1000.0)
.register(meterRegistry);
void cleanupExpiredSessions() {
removeExpiredBatch();
lastCleanup.set(System.currentTimeMillis()); // only after a successful run
}
// alert when the age is above 15 minutes, three missed 5-minute runs

A count of runs is less useful, because it says nothing when runs stop. The age of the last success rises steadily as soon as anything goes wrong, starvation, exceptions or a stuck run, so one alert covers all of them.

6Fix 4: Make Cleanup Incremental

Finally, a cleanup that removes everything in one pass can take a long time after a backlog, holding locks or a database connection and competing with request work. Making it incremental, removing at most a fixed number of items per run, keeps each run short and predictable. If a run removed a full batch, there is probably more, and it can run again soon; otherwise it waits for the next interval. Short runs also make the metric above meaningful, because a single run never looks stuck for an hour.

7Follow-up questions

Why not give the cleanup task a higher priority in the shared queue?

It would help the cleanup but keep the other problems: maintenance still depends on the request pool's workers, which might all be stuck on a slow dependency, and the unbounded queue still grows. Separate capacity is simpler and more robust than priorities, which also add the risk of starving the request tasks instead.

Does using virtual threads change this?

If request work runs on a virtual thread per task, there is no queue of tasks waiting for workers, so the cleanup would not wait behind them in the same way. But other shared resources, such as connection pools, would still be contended, and memory would still grow under overload without limits, so the maintenance isolation and the explicit limits still apply.

How large should the dedicated maintenance executor be?

Usually one thread is enough for a few periodic jobs, as long as each run is short. If several independent jobs exist and one can be slow, give the slow one its own executor so it cannot delay the others, which is the same isolation idea applied again.

8Conclusion

In this answer, we saw that a periodic cleanup submitted to a shared request pool is starved under steady load: it waits behind a constantly full queue, and memory grows from both uncollected data and the unbounded queue itself. The fixes are to run maintenance on its own scheduled executor, bound the request queue so overload becomes fast rejections, track the time since the last successful cleanup with an alert, and make cleanup incremental so each run is short.

What to say in the interviewAbout 90 seconds aloud

Open with

The cleanup task is starved. It is submitted to the same pool as request work, and that pool uses a FIFO queue, unbounded if it came from newFixedThreadPool.

Then, if they want more

Under steady high load the queue never drains, so a cleanup submitted every five minutes lands behind maybe millions of request tasks. If the pool completes 500 tasks a second and two million are queued, the cleanup starts more than an hour late.

Meanwhile memory grows twice over: expired data that the cleanup should remove keeps accumulating, and the queue itself holds millions of pending tasks. The thread dump looks fine, all workers busy, so it is easy to mistake for a leak. I would fix it in four ways.

First, maintenance gets its own ScheduledExecutorService, even one thread, using scheduleWithFixedDelay, so it never competes with requests. Second, I would bound the request queue, for example an ArrayBlockingQueue sized for a few seconds of work, and reject with a 503 when it is full, because requests that wait an hour are useless anyway.

Third, I would publish the time since the last successful cleanup as a gauge and alert when it passes a few intervals, which catches starvation, exceptions and hangs alike. Fourth, I would make the cleanup incremental, a bounded batch per run, so each run stays short even after a backlog.

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 service has one shared pool for request work and a periodic cleanup job. Under steady...": https://scrivio-interview-library.netlify.app/java/concurrency-problems/0a6c3902a3/