Lesson · Virtual Threads & Structured Concurrency
When to Use Virtual Threads: scale the waiting, bound the resource
15 min readWhen to Use Virtual Threads
Virtual threads fit work that waits: HTTP calls, JDBC, files, and the thread-per-request shape they make simple again. They do nothing for work that computes, because the carriers are cores. The migration is where the trap lives: removing the request pool also removes a concurrency limit you may have been relying on, so the limit has to move to the resource the tasks actually contend for.
The pool is gone, and so is the brake
Picture a service that was once rewritten into an asynchronous pipeline because requests blocked. The migration back is one line: point the request handler at a virtual-thread executor. The code gets simpler and the throughput improves, so the old pool is deleted with some satisfaction. Two weeks later there is an incident.
The database is timing out under a traffic spike. Nothing was slow and nothing was broken: 10,000 virtual threads reached the same connection pool, waits grew without a ceiling, and timeouts turned into retries. The thread pool that everyone was glad to delete had also been the thing keeping pressure away from the database.
That is the shape of this lesson. Virtual threads are for waiting; the limits you remove when you delete the pool have to be re-added where the contention actually is.
Removing the pool removes a limit you may have been relying on. Decide where the new one belongs before an incident decides for you.
Scale waiting, not computing
The JEP is specific about when virtual threads help: a high number of concurrent tasks (more than a few thousand) on a workload that is not CPU-bound. Both halves matter, and both are about waiting. If tasks spend their time parked on a socket or a query, thousands of them can share a handful of carriers; if they spend their time in arithmetic, the carrier is busy and the number of threads changes nothing.
Little's Law is the arithmetic behind the throughput claim: concurrency = throughput x latency. The JEP's own example uses 50 ms of latency. At 200 requests per second, 10 requests are in flight at any moment. Scale to 2,000 per second and 100 must be in flight. With platform threads those 100 in-flight requests are 100 OS threads; with virtual threads they are 100 parked tasks on a few carriers.
One expectation to drop on the way in: latency. A single request is not faster because it runs on a virtual thread. The same work happens in the same order on the same machine; what changes is how many requests can be waiting at the same time, which is throughput.
- Profile first: if the request path spends its time in WAITING and TIMED_WAITING, this is the workload virtual threads were built for.
- Keep the blocking code blocking: JDBC, HTTP clients, file reads. The sequential shape is the point, not a compromise.
- High concurrency is the sweet spot: a handful of tasks per second behaves exactly as before.
- Latency is unchanged: migrate for throughput, and measure the thing you are migrating for.
Virtual threads scale waiting, not computing.
CPU-bound work does not get faster
A CPU-bound task gets nothing from virtual threads. The carriers are platform threads, and there are about as many of them as there are cores; a core still runs one stream of instructions at a time. Ten thousand virtual threads doing arithmetic run on a few cores with an invisible queue in between, at precisely the throughput of a bounded platform pool.
There is a second, subtler cost. The scheduler does not implement time sharing for virtual threads, so a long calculation holds its carrier until it blocks or finishes. Virtual threads that compute are therefore not just useless for that work; they also add latency to everything else that wants those carriers. Keep heavy computation on a pool sized to the cores, or in a parallel stream, and let the virtual-thread side of the application do what it is for: wait efficiently.
Mixed workloads want both halves. Fetch with virtual threads, compute on a bounded pool, and decide by what the task spends its time doing rather than by what makes for a modern-sounding architecture.
| Workload | What limits it | Reach for |
|---|---|---|
| Request handling that waits (HTTP, JDBC, files) | the things being waited on | virtual threads, thread per request |
| Batch computation on in-memory data | cores | a bounded platform pool or parallel streams |
| Fetch, compute, fetch | cores during the compute step | virtual threads for the fetching, a sized pool for the computation |
| Tasks that mostly sleep or park | very little | virtual threads: it is the free case |
More threads do not make arithmetic faster; they only make waiting cheaper.
What changes in a migration
The mechanical part of a migration is one line. The habits are the real work, and the JEP names two of them plainly: do not pool virtual threads in order to limit concurrency, and be careful with thread-local caches of expensive resources, because a resource cached per thread becomes a resource built per task.
// Before: a pool of 200 platform threads shaped the whole design. ExecutorService pool = Executors.newFixedThreadPool(200); // After: one virtual thread per task, no queue in front of the threads. ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
- Swap the executor for one virtual thread per task and delete the sizing constant. Keep the shutdown path: the lifecycle still belongs to you.
- Audit every ThreadLocal that caches something expensive (connections, buffers, formatters). With one thread per task, a per-thread cache becomes a per-task allocation; move shared resources into a real pool or an explicit dependency.
- Find the places where the old pool was the de facto concurrency limit and ask what they were really protecting. Put the limit on that resource: a bounded database pool, a semaphore around the scarce client, a rate limiter for a dependency.
- Give the new waits an end: timeouts on the resource, metrics on its queue, and a plan for what happens when it is full.
- Load-test the waiting paths, not just the happy path. In a virtual-thread migration the first component to fall over is usually a downstream service, not the JVM.
- Check for pinning on the JDK you deploy, which for Java 21 means long synchronized sections that block; the previous lesson covers the diagnosis.
The pool was never the design; it was the budget. Move the budget to the resource.
Limit the resource, not the thread count
The old idiom used the thread pool as a brake: a pool of 20 meant at most 20 concurrent calls to the fragile service. That worked because threads were expensive and because the queue in front of the pool absorbed the rest of the demand.
With virtual threads the brake is gone, and that is mostly good: thousands of requests can wait cheaply instead of queueing behind a fixed set of workers. What must not disappear is the limit itself. If the database can serve 10 connections, then 10 is the number that matters, and a migration that removes every limit converts a bounded queue into unbounded pressure: growing waits, timeouts, retries, and a database that falls over in the middle of the storm.
So keep a limit and move it to where it belongs: a bounded connection pool, a semaphore around the scarce client, a rate limiter for the dependency. Waiting on it is cheap now, which is exactly why having thousands of tasks parked in front of a resource that can only serve ten is safe. Add timeouts so a wait can end, and metrics so the queue is visible where it actually forms.
| Old idiom (platform threads) | New shape (virtual threads) |
|---|---|
| A pool of 200 caps concurrent requests | limit the downstream resource, not the request count |
| Pool size stands in for the capacity of a dependency | the same number, expressed as a resource pool or a semaphore |
| A ThreadLocal caches one connection per worker | one shared bounded pool, borrowed per task |
| The queue in front of the pool absorbs bursts | timeouts plus metrics make the wait visible and finite |
Limit the resource, not the thread count.
where the limit belongs
the requests become cheap; the resource stays scarce10,000 requests
each one waits on a connection, a socket or a partner service
virtual threads · one per task
waiting costs heap, not an OS thread, so nothing caps the count here
no request pool, no queue in front of the request handlers
the scarce resource · connections, quotas, cores
bound it here: a bounded pool, a semaphore, a rate limiter, all with a timeout
thousands may park in front of it, and that is affordable; unbounded pressure is not
pick the tool by what the task spends its time doing
tasks wait (IO-bound)
virtual threads, thread per request
the wait is what got cheap, so this is the shape that scales waiting
tasks compute (CPU-bound)
bounded platform pool sized to cores
carriers are cores; extra threads add latency, not throughput
a dependency is scarce
a limit on that dependency
the limit should express its capacity, not a thread count
Virtual threads do not remove limits; they move where limits must be expressed. The JEP recommends constructs designed for the job, such as semaphores, instead of a pool of virtual threads, and warns that per-thread caches of expensive resources become per-task allocations when every task gets its own thread.
Run the combinations
The lab below is the decision in this lesson: three workloads against three threading shapes. None of it is a benchmark; all of it is the argument you would make in a design review.
Same machine, same task, different limit: that is the whole migration.
decision lab · workload and threading
click a workload, then a threading shapeworkload
each task waits on a remote service and computes almost nothing
threading
200 OS threads, a queue in front of them
10,000 short IO calls × platform pool (200)
outcome
works, but the pool decides how many waits share the machine
200 calls in flight, the other 9,800 queue in the executor. Throughput is capped by the pool size, and each worker costs an OS thread with a stack of its own. This is the design virtual threads replace.
what is actually limited: the pool size (200), chosen in advance and paid for in threads
When not to use virtual threads
Virtual threads are not a general upgrade, and treating them as one produces new incidents with modern vocabulary. The cases that want something else:
- CPU-bound work: cores decide throughput, so use a bounded platform pool sized to the hardware, or a parallel stream.
- Code that depends on thread identity or thread-local caches: per-thread state multiplied by thousands becomes memory pressure, and the next lesson in this part is about the replacement.
- Long synchronized sections around blocking calls on Java 21: pinning holds carriers; move the block out of the monitor, use java.util.concurrent locks, or run Java 24 or newer.
- Native-heavy paths: a native frame pins the carrier on every version; keep those calls short or move them to a dedicated platform thread.
- Priority-based designs: setPriority is ignored on a virtual thread, and the scheduler does not read it.
- A hard concurrency cap you can point at: express it as a semaphore or a resource pool, since a thread count no longer exists to cap.
Virtual threads are a scheduler for waiting tasks, not a faster engine for anything.
What to remember
Four sentences carry the decision:
- Waiting scales, computing does not: high concurrency on IO-bound work is the sweet spot; cores still bound arithmetic.
- Thread-per-request is back: remove the request pool, keep the simple sequential handler.
- Move the limit to the resource: bounded pools, semaphores and rate limiters around the scarce dependency, with timeouts and metrics.
- Throughput, not latency: a virtual thread does not make one request faster, it lets more of them wait at once.
Virtual threads scale the number of tasks in flight, and the moment you remove the pool, some resource becomes the new ceiling.
The migration that flooded the database
The swap was one line, deleting the pool was celebrated, and the incident arrived with the first traffic spike: 10,000 virtual threads reached the same pool of 10 connections, waits grew without bound, and timeouts turned into retries. Nothing was broken; the brake had been removed. The fix is not to restore the request pool. It is to put the limit on the connection pool or the client, add timeouts and metrics, and let the virtual threads wait cheaply behind it.
Interview angles
When do virtual threads improve throughput?+
When concurrency is high (the JEP names more than a few thousand concurrent tasks) and the workload is not CPU-bound. Those are exactly the conditions where the tasks spend their time waiting, which is what becomes cheap.
Little's Law links the numbers: at 50 ms of latency, 2,000 requests per second requires about 100 requests in flight. Virtual threads let those 100 in-flight requests be 100 parked tasks instead of 100 OS threads.
Would you run CPU-bound work on virtual threads?+
No. Carriers are platform threads and there are about as many as cores, so throughput is unchanged. The scheduler also does not time-share, so a long calculation holds its carrier and adds latency to everything else on it.
A bounded platform pool sized to the available cores, or a parallel stream for data-parallel work.
Follow-up: What do you use instead?
You replaced the thread pool and the database started timing out. What happened?+
The request pool was also the concurrency limit. Without it, thousands of virtual threads pile up in front of a resource that can serve a much smaller number, and the wait needs bounds. Cap the resource (connection pool, semaphore, rate limiter) and add timeouts.
Common misconception: That the fix is to restore the request thread pool. The pool limited the wrong thing; the limit belongs on the dependency that cannot serve the load.
Why is a limit expressed as a thread count the wrong shape now?+
Because thread count is no longer a scarce resource, so capping it says nothing about the system. Express the limit as the capacity of the thing being contended for: connections, calls per second, concurrent exports.
Waiting behind that limit is cheap, which is the difference: the same limit that would have queued hundreds of expensive threads now parks thousands of cheap ones, visible in metrics rather than in pool saturation.
Do you still need thread pools?+
Yes, for the cases virtual threads do not cover: CPU-bound work, native calls that pin, work that must run on a dedicated platform thread, and resources that genuinely need pooled reuse.
What disappears is the request pool, the one that existed to share the cost of threads across tasks that only wait.
Does a virtual thread make a single request faster?+
No. They exist to provide scale (higher throughput), not speed (lower latency); the JEP is explicit about that. The request does the same work on the same machine.