Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

During an incident, a thread dump shows 900 threads named like pool-3-thread-17 and Thread-212, and nobody can tell which component created them. What would you change in the codebase and in operations?

In the codebase, we require every executor to use a named ThreadFactory with a component prefix, set a default uncaught exception handler at startup so silent thread deaths are logged, and look for code that creates raw threads or executors that are never closed, which usually explains a rising thread count. In operations, we track thread counts per name prefix as a metric to detect leaks such as an executor created per request, and capture thread dumps automatically when thread count or latency alerts fire, so the next incident starts with evidence.

Why this question is asked

A thread dump is the X-ray of a Java service, but an X-ray with no labels is hard to read. Nine hundred threads called pool-3-thread-17 and Thread-212 tell us that something is wrong and nothing about where. Interviewers ask this scenario to see whether we can turn one painful incident into lasting changes in both code and operations. In this answer, we will first read what the dump already tells us, then go through the code changes (named factories, a default exception handler, finding leaks) and the operational changes (per-prefix metrics and automatic dumps), with examples for each.

1Reading What the Dump Already Tells Us

Even anonymous names carry clues. pool-N-thread-M comes from Executors.defaultThreadFactory(): N is the number of the pool in the JVM and M the thread within that pool. A dump with pool-3 through pool-214 means more than two hundred executors were created, which almost always means an executor created per request or per call and never shut down. Thread-N comes from new Thread() without a name, so those are raw threads someone started by hand.

The stack of each thread is the other clue. Grouping threads by their top frames shows what they are doing: hundreds parked in LinkedBlockingQueue.take() are idle pool workers waiting for tasks that will never come, which confirms leaked executors. A quick script or a tool such as a thread dump analyser can do this grouping in seconds.

Shell
$ jcmd 4123 Thread.print > dump.txt
$ grep -o '^"[^"]*"' dump.txt | sed -E 's/[0-9]+/N/g' | sort | uniq -c | sort -rn | head -4
690 "pool-N-thread-N" // about 230 pools of 3 threads: executors leaked
150 "Thread-N" // raw threads
40 "http-nio-N-exec-N" // Tomcat workers, expected
20 "HikariPool-N ..." // connection pool helpers, expected

Notice how the framework threads, Tomcat and Hikari, are easy to recognise because their authors named them. Our own code is the anonymous part. That is what we change.

2Code Change 1: A Named ThreadFactory for Every Executor

The rule is simple: no executor may use the default thread factory. Every executor gets a factory whose prefix names the component, such as pricing-client-, report-export- or kafka-retry-. We make this easy by providing one helper in the shared library and making the raw constructors fail code review.

Java
public final class Executors2 {
public static ExecutorService fixed(String component, int threads) {
ThreadFactory f = Thread.ofPlatform()
.name(component + "-", 1)
.uncaughtExceptionHandler(Handlers.LOG_AND_COUNT)
.factory();
return Executors.newFixedThreadPool(threads, f);
}
}
ExecutorService pricing = Executors2.fixed("pricing-client", 8); // pricing-client-1 ... -8

In Spring, ThreadPoolTaskExecutor and ThreadPoolTaskScheduler have setThreadNamePrefix(), and Spring Boot exposes spring.task.execution.thread-name-prefix for its own executor. A build-time check, for example an ArchUnit rule or a static analysis rule that bans Executors.newFixedThreadPool(int) without a factory and new Thread(Runnable) without a name, keeps the rule from eroding.

3Code Change 2: A Default Uncaught Exception Handler

Some of those threads may have died with exceptions that nobody saw, because the default behaviour prints to System.err, which may not reach our logs. Setting a default handler once at startup covers every thread that has no handler of its own.

Java
public static void main(String[] args) {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
log.error("Thread {} died", t.getName(), e);
Metrics.counter("threads.uncaught", "prefix", prefixOf(t.getName())).increment();
});
SpringApplication.run(App.class, args);
}

Remember that this only catches exceptions that escape a thread. Tasks passed to submit() keep their exceptions in the Future, so the handler does not replace proper error handling in tasks.

4Code Change 3: Find the Leaks Behind the Count

A dump with hundreds of pools almost always points to code like the example below, where an executor is created inside a method that runs per request.

Java
// Leaks one pool of 3 threads per call
List<Price> prices(List<Item> items) {
ExecutorService ex = Executors.newFixedThreadPool(3); // new pool every request, never shut down
return items.stream().map(i -> ex.submit(() -> pricing.get(i))).map(this::join).toList();
}
// Fixed: one shared, named, bounded executor for the component
private final ExecutorService pricingPool = Executors2.fixed("pricing-client", 8);
Step throughFrom an anonymous dump to a root cause
  1. Group threads by name patternpool-N-thread-N: 690
  2. Many distinct pool numbers?
    YesExecutors created per callNoOne pool, check its size
  3. Search code for executor creation in methodsExecutors.new... inside request paths
  4. Replace with one shared named executoror close it after use

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

Non-daemon pool threads that are never shut down stay alive forever, so the count grows with traffic until the JVM runs out of memory for thread stacks or hits the OS thread limit. If an executor really is needed for one call, it should be closed, for example with try-with-resources on Java 19 and later, where ExecutorService is AutoCloseable. Raw threads named Thread-N deserve the same search: each should either become a task on a named executor or at least get a name and an owner.

5Operations: Per-Prefix Metrics and Automatic Dumps

Named threads make a new metric possible: live threads per prefix. A small gauge that groups Thread.getAllStackTraces() keys, or the ThreadMXBean's thread ids, by name prefix every minute is enough. A healthy service has flat lines per prefix; a leak shows as one prefix rising with traffic, which we can alert on long before the dump reaches 900. The JVM-wide thread count (Micrometer's jvm.threads.live) gives the overall alert, and the per-prefix breakdown tells us where to look.

Finally, the evidence should be captured automatically. When a thread-count or latency alert fires, a small runbook automation or sidecar runs jcmd <pid> Thread.print two or three times a few seconds apart and stores the output with the alert. Several dumps in a row show which threads are stuck and which are moving, and the incident starts with data instead of with someone trying to attach to a pod that may already have been restarted.

6Follow-up questions

How do we name threads created by third-party libraries?

Many libraries accept a ThreadFactory or an executor in their configuration, so we pass a named one. For those that do not, we at least learn their default names and document them. Well-known libraries usually already name their threads, as Tomcat and HikariCP do.

Would virtual threads make the leak harmless?

They would make each leaked thread cheaper, but a leaked executor is still a bug that holds tasks and memory. Virtual threads are also unnamed by default and do not appear in the classic jstack output; jcmd Thread.dump_to_file includes them. Naming them through Thread.ofVirtual().name(...) is just as important.

What is a reasonable alert threshold for thread count?

There is no universal number. We baseline each service: for example, if a service normally runs 120 to 150 threads, an alert at 300 sustained for ten minutes catches leaks without noise. Per-prefix growth that tracks traffic is an even better signal than a fixed threshold.

7Conclusion

In this answer, we read the anonymous dump for clues: many pool-N numbers mean executors created per call, and Thread-N means raw threads. In the codebase we required a named ThreadFactory with a component prefix for every executor, set a default uncaught exception handler, and fixed leaks from executors created per request or raw threads. In operations we added thread counts per prefix as a metric with alerts and automatic thread dumps when alerts fire, so the next incident starts with evidence.

What to say in the interviewAbout 90 seconds aloud

Open with

First I'd note that the dump isn't completely useless. pool-N-thread-M names come from the default thread factory, and if N goes into the hundreds, it means hundreds of executors were created, which nearly always means someone creates an executor per request and never shuts it down.

Then, if they want more

Thread-N means raw threads started by hand. Grouping the dump by name pattern and top stack frame usually confirms it: lots of idle workers parked in take. In the codebase I'd make three changes.

Every executor must use a named ThreadFactory with a component prefix, like pricing-client-1, provided by a small helper in our shared library, or setThreadNamePrefix in Spring, and enforced with an ArchUnit or static analysis rule. I'd set a default uncaught exception handler at startup that logs and counts per prefix, so threads don't die silently to standard error.

And I'd search for executor creation inside request paths and raw new Thread calls, replacing them with one shared bounded executor or closing them properly. In operations, I'd add a metric of live threads per prefix, so a leak shows up as one prefix climbing with traffic, with alerts on that and on the total count.

And when a thread-count or latency alert fires, automation should take two or three thread dumps a few seconds apart and attach them to the alert, so we start the next incident with evidence.

About this answer

Last updated
12 November 2026
Versions it names
Java 19
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 "During an incident, a thread dump shows 900 threads named like pool-3-thread-17 and...": https://scrivio-interview-library.netlify.app/java/threads/22c5ca89eb/