Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A service uses Executors.newFixedThreadPool(20) to send events to a slow downstream. During a downstream slowdown the service runs out of heap. Explain the cause and the fix.

Executors.newFixedThreadPool(20) creates a pool with 20 threads and an unbounded LinkedBlockingQueue, so when the slow downstream keeps all 20 threads busy, every new task waits in the queue without limit, and each queued task holds its event data until the heap is full. The fix is a ThreadPoolExecutor with a bounded queue and a deliberate rejection policy: CallerRunsPolicy slows the producers down as backpressure, while AbortPolicy lets us shed load or return an error. We also monitor queue depth and task latency and protect the downstream calls with timeouts and a circuit breaker.

Why this question is asked

This incident has happened in many production systems, and it usually starts with a line that looks completely safe. A fixed pool sounds bounded: we asked for 20 threads, after all. The surprise is that the bound applies only to threads, not to the work waiting for them. Interviewers ask about it because it tests whether we know what the Executors factory methods actually create and whether we think about overload, not just the happy path. In this answer, we will reproduce the failure, open up what newFixedThreadPool builds, calculate how fast the heap fills, replace it with a bounded executor, compare the rejection policies, and add the monitoring and downstream protection that make the fix complete.

1Reproducing the Problem

The service receives events from an API or a message listener and forwards each one to a downstream system with a blocking HTTP call. The forwarding runs on a fixed pool so that the request threads are not held up.

Java
private final ExecutorService sender = Executors.newFixedThreadPool(20);
public void onEvent(Event event) { // called about 2,000 times per second
sender.submit(() -> downstream.send(event)); // normally takes 5 ms
}
// Downstream slows to 1,000 ms per call:
// java.lang.OutOfMemoryError: Java heap space

In normal operation, 20 threads at 5 ms per call can handle 20 / 0.005 = 4,000 calls per second, double the incoming rate, so nothing queues. Then the downstream slows down to one second per call. Capacity falls to 20 calls per second while 2,000 events per second keep arriving.

2What newFixedThreadPool Really Creates

The factory method is a thin wrapper around ThreadPoolExecutor, and the queue it chooses is the key detail.

Java
// The JDK's implementation, in essence
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()); // no capacity given: Integer.MAX_VALUE
}
Step throughHow the heap fills during a slowdown
Event sourceFixed pool (20 threads)Unbounded queueSlow downstream
submit(task) x 2,000 per second
20 calls in flight, 1 s each
1,980 tasks per second wait here
grows about 20 MB per second, never full
20 calls complete per second
OutOfMemoryError after minutes

6 messages in order. Play them, or step through them one at a time.

The pool bounds threads, not waiting work, so the queue absorbs the whole overload.

A LinkedBlockingQueue created without a capacity accepts up to Integer.MAX_VALUE tasks, about 2.1 billion, which in practice means it never says no. So when all 20 threads are busy, submit() always succeeds: the task goes into the queue and the caller returns immediately, unaware that the work is piling up.

Each queued task is a lambda that captured the event, so the event object, its payload and the task wrapper all stay reachable until a thread gets to it. With 1,980 extra tasks per second and, say, 10 KB per event, the queue grows by about 20 MB per second. A 4 GB heap is gone in a little over three minutes. The garbage collector cannot help because every one of those objects is still referenced by the queue. Notice the irony too: by the time the downstream recovers, the oldest queued events are minutes old, so even the work that does get sent may be useless.

3The Fix: A Bounded Queue and a Rejection Policy

We build the ThreadPoolExecutor ourselves, so that we choose every part: the number of threads, a queue with a capacity, thread names that show up in thread dumps, and what happens when the queue is full.

Java
private final ThreadPoolExecutor sender = new ThreadPoolExecutor(
20, 20, // core and max threads
0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1_000), // at most 1,000 waiting events
Thread.ofPlatform().name("downstream-sender-", 0).factory(),
new ThreadPoolExecutor.CallerRunsPolicy()); // when full, the caller runs the task
// Worst-case memory for waiting work: 1,000 x 10 KB = about 10 MB

Now the queue holds at most 1,000 tasks. When it is full, the executor calls its rejection handler instead of queueing. The capacity should come from how long we are willing to let an event wait: with 20 calls per second during an incident, 1,000 queued tasks already means 50 seconds of delay, so a smaller queue may be better.

4Choosing the Rejection Behaviour

The rejection handler decides who pays for the overload, and the right choice depends on where the events come from. CallerRunsPolicy runs the task on the thread that called execute. That thread is now busy sending an event, so it cannot submit more, which slows the producer to the pool's pace. If the producer is a Kafka consumer thread, that is ideal backpressure: consumption slows, unprocessed messages stay safely in Kafka, and the lag metric shows it. If the producer is an HTTP request thread, the requests become slow instead, which may be acceptable or may exhaust the web server's threads.

AbortPolicy, the default, throws RejectedExecutionException from submit. The caller can catch it and shed load deliberately: return 503 Service Unavailable so the client retries later, write the event to a durable retry store, or drop low-value events and count them. DiscardPolicy and DiscardOldestPolicy drop tasks silently, which is rarely acceptable for events because nothing records what was lost.

Rejection policies when the bounded queue is full
PolicyWhat happensGood fit
CallerRunsPolicySubmitting thread runs the task itselfKafka or batch producers: natural backpressure
AbortPolicysubmit throws RejectedExecutionExceptionReturn 503, store for retry, or count and shed
DiscardPolicyTask is dropped silentlyRarely: only truly disposable work
DiscardOldestPolicyOldest queued task is droppedLatest-value updates such as prices

5Monitoring and Protecting the Downstream

A bounded queue stops the crash, but we also want to see the problem coming and make the slow calls cheaper. ThreadPoolExecutor exposes getActiveCount(), getQueue().size() and getCompletedTaskCount(), and Micrometer's ExecutorServiceMetrics can publish them, so dashboards show queue depth, active threads and rejections. Measuring task latency, from submit to completion, tells us how stale events are. An alert on queue depth above, say, 50 percent of capacity fires long before rejections start.

The root cause is still the slow downstream. Every call should have a connect and read timeout, perhaps 2 seconds, so a hanging downstream cannot hold a thread forever. A circuit breaker, for example from Resilience4j, stops calling the downstream for a while after the failure rate crosses a threshold, so threads are freed instantly and the downstream gets room to recover. Together, timeouts, a circuit breaker and a bounded pool turn a slowdown into a visible, contained degradation instead of an outage.

6Follow-up questions

Do the other Executors factory methods have the same problem?

newSingleThreadExecutor also uses an unbounded LinkedBlockingQueue. newCachedThreadPool uses a SynchronousQueue with an unbounded maximum pool size, so instead of queueing it creates a new thread for every task during a slowdown, which can exhaust memory or native threads even faster. newScheduledThreadPool uses an unbounded delay queue. For production services, building the ThreadPoolExecutor explicitly is the safer habit.

Is it better to block the producer instead of rejecting?

Blocking is what CallerRunsPolicy approximates. Some teams use a custom handler that calls queue.put to block the caller until space frees up, but that can block request threads indefinitely and hides the overload. A bounded wait, such as offer with a timeout followed by rejection, is a safer variation.

Would virtual threads fix this?

Not by themselves. A virtual thread per task would start all 2,000 calls per second against a downstream that can handle 20, so the number of in-flight calls and their captured events would grow just as fast. We would still need a limit, such as a semaphore around the call, plus timeouts and a circuit breaker.

7Conclusion

In this answer, we saw that Executors.newFixedThreadPool bounds threads but uses an unbounded LinkedBlockingQueue, so during a downstream slowdown every task waits in the queue holding its event until the heap is exhausted. The fix is an explicit ThreadPoolExecutor with a bounded queue, named threads and a rejection policy chosen for the producer: CallerRunsPolicy for backpressure, AbortPolicy to shed load or return errors. Metrics on queue depth, task latency and rejections show the problem early, and timeouts and a circuit breaker on the downstream address its cause.

What to say in the interviewAbout 90 seconds aloud

Open with

The trap is that newFixedThreadPool only bounds the threads. Internally it is a ThreadPoolExecutor with core and max both 20 and a LinkedBlockingQueue with no capacity, so effectively unbounded.

Then, if they want more

In normal operation 20 threads at a few milliseconds per call keep up easily. When the downstream slows to a second per call, the pool can do 20 calls a second while 2,000 events keep arriving, and every submit still succeeds by adding to the queue.

Each queued task captured its event, so all those events stay reachable, the queue grows by tens of megabytes a second, and the heap fills in minutes. GC cannot help because the queue references everything. The fix is to create the ThreadPoolExecutor explicitly with a bounded ArrayBlockingQueue, named threads, and a rejection policy chosen on purpose.

CallerRunsPolicy makes the submitting thread run the task, which slows the producer down, ideal if the producer is a Kafka consumer since messages just wait in Kafka. AbortPolicy throws RejectedExecutionException so I can return 503, store for retry or shed load and count it.

Then I add metrics for queue depth, active threads, rejections and task latency, with an alert well before the queue is full, and I protect the downstream itself with timeouts and a circuit breaker so slow calls stop holding threads.

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 service uses Executors.newFixedThreadPool(20) to send events to a slow downstream....": https://scrivio-interview-library.netlify.app/java/concurrency-patterns/168f9c9ff6/