Quick revision
The short answer
I would set one main rule: application code never creates raw threads or unbounded pools; it uses named, managed executors injected from a shared platform module. Blocking I/O work defaults to virtual threads, CPU-bound work uses a bounded platform pool sized to the available cores, and every executor has names, exception handling, metrics, timeouts and graceful shutdown. Rules are enforced with ArchUnit or Error Prone checks, with a reviewed exception process and help to migrate existing code.
What to remember
In this answer, we saw why raw threads, cached pools, ad hoc factories and default @Async each cause trouble at scale, and set rules to replace them: executors are named, managed beans injected from the platform; blocking I/O defaults to virtual threads while CPU work uses bounded pools sized to cores; there are no unbounded pools and every wait has a timeout; and every executor has names, error handling, metrics and graceful shutdown. We enforce the rules with ArchUnit or Error Prone in the build, allow reviewed exceptions, and migrate existing code by risk with real help from the platform team.
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.
I would set one main rule: application code never creates raw threads or unbounded pools; it uses named, managed executors injected from a shared platform module. Blocking I/O work defaults to virtual threads, CPU-bound work uses a bounded platform pool sized to the available cores, and every executor has names, exception handling, metrics, timeouts and graceful shutdown. Rules are enforced with ArchUnit or Error Prone checks, with a reviewed exception process and help to migrate existing code.
Why this question is asked
In a large codebase, thread creation spreads quietly. One team writes new Thread for a quick background job, another uses Executors.newCachedThreadPool because the tutorial did, a third relies on @Async without checking which executor it uses. Each choice is local, but the failures are global: thread leaks, pools that grow without limit, lost exceptions, and shutdowns that cut work in half. Interviewers ask this at senior levels to see whether we can turn concurrency knowledge into rules that hundreds of engineers can follow. In this answer, we will look at what goes wrong with each pattern in the question, set out the rules, explain how virtual threads change them, and see how to enforce and roll them out.
1What Goes Wrong With Each Pattern Today
It helps to start from the failures, because each rule exists to prevent one. A raw new Thread has no limit, no name worth reading in a thread dump, no place where its exceptions are counted, and nobody waits for it on shutdown. Executors.newCachedThreadPool creates a new thread whenever all existing threads are busy, with no upper bound, so a slow downstream service turns into thousands of threads. Custom thread factories are usually fine, but each team writes its own, with different names, daemon settings and error handling.
@Async is the subtle one. In plain Spring Framework, if no executor bean is found, @Async falls back to SimpleAsyncTaskExecutor, which starts a new thread for every call. Spring Boot auto-configures an applicationTaskExecutor (a bounded ThreadPoolTaskExecutor by default, or a virtual-thread executor when spring.threads.virtual.enabled=true), but whether a service gets it depends on its configuration. Teams often do not know which one they are running.
| Pattern | Main risk | Rule |
|---|---|---|
new Thread(...).start() | unbounded, unnamed, errors and shutdown lost | banned in application code |
Executors.newCachedThreadPool() | grows without limit under slow I/O | banned for request-driven work |
Custom ThreadFactory per team | inconsistent names and error handling | use the shared factory |
@Async with defaults | may be a thread per call (SimpleAsyncTaskExecutor) | always name the executor |
| Injected, managed executor bean | none of the above | the default |
2Rule 1: Executors Come From the Platform, Not From Application Code
The central rule is that application code asks for an executor; it never builds one. A shared platform library, or the Spring configuration of each service, defines a small set of named executor beans, for example ioExecutor and cpuExecutor, and code receives them through injection. In Spring that means TaskExecutor or ExecutorService beans, and every @Async names its executor explicitly, as in @Async("ioExecutor").
The reason is ownership. When an executor is a bean, the platform team can give it a name, metrics, a shutdown hook and sensible limits once, and every user gets them. When an incident happens, a thread dump shows io-142 or cpu-3 instead of Thread-9831, and we know which pool to look at.
Notice that the two beans encode the second rule as well. Work that mostly waits on I/O goes to virtual threads; work that burns CPU goes to a bounded platform pool sized to the cores, because more CPU threads than cores only adds context switching.
3Rule 2: Virtual Threads for Blocking I/O, Bounded Pools for CPU
Virtual threads change the old sizing debate for I/O work. We used to size I/O pools carefully, say 200 threads, because each one was an operating system thread. A virtual thread costs a few hundred bytes until it runs, so the default for blocking calls to databases, HTTP services and message brokers becomes one virtual thread per task. On Spring Boot 3.2 and later, spring.threads.virtual.enabled=true switches request handling and the default task executor to virtual threads.
But the guideline must say what virtual threads do not do. They do not limit concurrency, so the limit moves to the resources: the database connection pool, a Semaphore around a fragile downstream service, or a rate limiter. They are also the wrong tool for CPU-bound work, which gains nothing from cheap blocking and should stay on a pool of about availableProcessors() platform threads. And code that holds a lock while doing long blocking work should be reviewed, since pinning behaviour depends on the JDK version (JDK 24 removed pinning for synchronized; check your version).
4Rule 3: No Unbounded Pools, and Every Wait Has a Time Limit
For platform-thread pools, the rule is simple: every pool has a maximum size, a bounded queue and an explicit rejection policy. An unbounded queue hides overload until memory runs out, and an unbounded pool size hides it until thread creation fails. A deliberate rejection, counted in metrics, turns overload into a visible, testable event.
Every wait must also have a time limit: future.get(2, SECONDS) instead of get(), HTTP and database clients with connect and read timeouts, and invokeAll with a timeout. Without timeouts, a bounded pool fills with threads stuck on a dead service, and the bound only changes which error we see.
5Rule 4: Every Executor Is Observable and Shuts Down Cleanly
The checklist for an executor is short and fixed. It has a thread name prefix. It has an uncaught exception handler or wraps tasks so failures are logged and counted, because exceptions inside execute() otherwise go to stderr. It publishes metrics through Micrometer's ExecutorServiceMetrics: active threads, queue size, completed tasks and rejections. And it is closed on shutdown, waiting a bounded time for running tasks, which Spring does for executor beans when graceful shutdown is configured.
These four items are what make an incident short. With them, a dashboard shows that the io pool queue grew from 0 to 900 at 14:02, and a thread dump shows where its threads are waiting.
6Enforcing and Rolling Out the Rules
Rules that live only in a wiki decay within months, so we enforce them in the build. An ArchUnit test, shared by every service through the platform library, fails the build when application code calls the Thread constructor or Executors.newCachedThreadPool. Error Prone or Sonar rules can do the same at compile time. Exceptions are allowed but reviewed: a suppression annotation with a reason and an owner, so the rare legitimate case stays visible.
For the existing code, we start the rule in warning mode and publish a list of current violations per team, sorted by risk: request-driven new Thread and cached pools first, quiet batch jobs last. The platform team offers a migration guide with before and after examples, and pairs with the teams on the first few changes. After a set date, the rule turns into a build failure for new violations, while the remaining old ones are tracked down to zero.
The key judgment here is to make the right thing the easy thing. If injecting ioExecutor is one line and writing new Thread fails the build, engineers follow the rule without having to remember it.
7Follow-up questions
Why not simply turn on virtual threads everywhere and remove all pools?
Because virtual threads solve the cost of threads, not the cost of the work. CPU-heavy tasks still need a bounded pool sized to cores, and blocking calls still need limits that protect databases and downstream services. Some libraries also behave differently under virtual threads, for example those that use ThreadLocal caches heavily, so we enable them per service with load tests rather than as a global switch.
How do you handle a legitimate need for a raw thread?
Some cases are real, such as a long-lived background loop in a framework component or a shutdown hook. The rule allows them inside the platform package, or with a reviewed suppression that names the reason and an owner. The goal is not zero threads, it is zero unowned threads.
How do you know the rules are working?
We track violations in the build over time, and we watch production signals: thread counts per service, executor rejections, queue sizes and incidents caused by thread exhaustion. If thread counts become flat and predictable and those incidents stop, the rules are doing their job.
8Conclusion
In this answer, we saw why raw threads, cached pools, ad hoc factories and default @Async each cause trouble at scale, and set rules to replace them: executors are named, managed beans injected from the platform; blocking I/O defaults to virtual threads while CPU work uses bounded pools sized to cores; there are no unbounded pools and every wait has a timeout; and every executor has names, error handling, metrics and graceful shutdown. We enforce the rules with ArchUnit or Error Prone in the build, allow reviewed exceptions, and migrate existing code by risk with real help from the platform team.
Open with
My main rule would be that application code never creates threads or pools itself. It gets named, managed executors injected from a shared platform module, and every @Async names its executor, because default @Async in plain Spring can fall back to a thread per call.
Then, if they want more
For blocking I/O, the default would be virtual threads, which on Spring Boot 3.2 and later is a property, but I would be clear that virtual threads do not limit concurrency, so database pools, semaphores or rate limiters protect downstream services. CPU-bound work goes to a bounded platform pool sized to availableProcessors, which respects container limits.
I would ban newCachedThreadPool and raw new Thread for request-driven work, require bounded queues and explicit rejection policies, and require timeouts on every wait and every client. Every executor must have a name prefix, exception handling that logs and counts failures, Micrometer ExecutorServiceMetrics, and graceful shutdown.
To make this stick, I would put ArchUnit rules in the shared test library, start them in warning mode with a list of violations per team, give a migration guide and pair on the first changes, then make new violations fail the build. Exceptions are allowed through a reviewed suppression with an owner.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 24, Spring Boot 3.2
- 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.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
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 "Your codebase has many places that create threads directly: new Thread...": https://scrivio-interview-library.netlify.app/java/threads/fb4ff2ceff/