Sub topic 7
When virtual threads help and when they do not
This chapter assumes you know the thread-per-request model, you can read a basic ExecutorService example, and you have a Spring Boot 3.2+ MVC application on Java 21. It also assumes you know the property that enables virtual threads. This chapter covers the decision: which applications gain from the switch, and which do not.
The working model
A virtual thread does not make code run faster. It makes waiting cheap. A platform thread that waits on a socket holds an operating system thread and its stack until the call returns. A virtual thread that waits gives up its carrier thread, so the carrier can run other virtual threads. The wait still takes as long as before.
This gives two rules:
- Throughput can rise when threads spend most of their time waiting, because you can have far more of them.
- Latency per request does not drop. A request that needs 80 ms of database time still needs 80 ms.
Both rules follow from Little's law, which says the number of requests in flight equals throughput multiplied by the average time each request takes:
concurrency = throughput x latencySuppose each request spends 100 ms, mostly waiting on a database and an HTTP service. At 2,000 requests per second, about 200 requests are in flight at once. Tomcat's default server.tomcat.threads.max is 200, so a platform-thread server saturates at roughly 2,000 requests per second for this workload. Extra requests queue, and latency climbs. With virtual threads, the thread count stops being the limit. In-flight requests can reach 2,000 or 20,000, and something else becomes the limit: CPU, a connection pool, or a downstream service.
Workloads that benefit
Virtual threads help most when all of these are true:
- Each request spends most of its time blocked on I/O such as JDBC, HTTP clients, message brokers, or file and network reads.
- Many requests are in flight at once, enough that the platform-thread pool is a bottleneck.
- The code is written in a plain blocking style that you would like to keep.
Typical examples are REST backends that call a database and two or three other services, and API gateways or aggregators that make several outbound calls per request.
Workloads that do not benefit
| Workload | Effect of virtual threads | Reason |
|---|---|---|
| CPU-bound (image resizing, hashing, report computation) | None, sometimes slightly worse | No waiting to hide. Parallelism is limited by core count. |
| Low concurrency (an internal tool with 20 users) | None visible | The platform pool never fills. |
| Blocked on a small connection pool | Little | The pool is the bottleneck, not threads. |
| Heavy `synchronized` sections that block | Can be worse | Pinning keeps the carrier occupied (a later chapter covers this). |
| Already reactive, non-blocking code | None | There is no blocked thread to remove. |
CPU-bound work is the clearest case. Virtual threads run on a small set of carrier threads, by default as many as there are available processors. If 200 virtual threads each burn CPU on an 8-core machine, only 8 run at a time. A pool of 200 platform threads has the same limit, because the operating system can only run 8 at a time too.
A quick experiment
The program below runs the same number of tasks on a fixed pool of platform threads and on a virtual-thread-per-task executor. It uses two kinds of task: one that sleeps for 100 ms to stand in for blocking I/O, and one that computes. ExecutorService implements AutoCloseable in Java 21, so try-with-resources waits for all tasks.
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;
public class WorkloadFit {
private static final LongAdder SINK = new LongAdder();
public static void main(String[] args) {
Runnable blocking = () -> {
try {
Thread.sleep(Duration.ofMillis(100));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Runnable cpu = () -> SINK.add(burn());
System.out.println("blocking, 200 platform threads: "
+ run(Executors.newFixedThreadPool(200), 10_000, blocking));
System.out.println("blocking, virtual threads: "
+ run(Executors.newVirtualThreadPerTaskExecutor(), 10_000, blocking));
System.out.println("cpu, 200 platform threads: "
+ run(Executors.newFixedThreadPool(200), 400, cpu));
System.out.println("cpu, virtual threads: "
+ run(Executors.newVirtualThreadPerTaskExecutor(), 400, cpu));
}
static Duration run(ExecutorService executor, int tasks, Runnable work) {
Instant start = Instant.now();
try (executor) {
for (int i = 0; i < tasks; i++) {
executor.submit(work);
}
}
return Duration.between(start, Instant.now());
}
static long burn() {
long x = 0;
for (int i = 0; i < 20_000_000; i++) {
x += i ^ (x >>> 3);
}
return x;
}
}Run it with java WorkloadFit.java. The exact numbers depend on your machine, but the pattern is stable:
- The blocking case takes about 5 seconds on 200 platform threads (10,000 tasks × 100 ms ÷ 200 threads). On virtual threads it finishes in a fraction of a second, because all 10,000 sleeps overlap.
- The CPU case takes about the same time on both executors, because both are limited by core count.
A decision path
The diagram turns the criteria into questions you can ask about a service before you change anything.
Checking your own service
You can answer the diagram's questions with data from a running service.
Is the thread pool the bottleneck?
Look for signs that requests wait for a worker thread before they run:
- Tomcat's busy thread count sits at
server.tomcat.threads.maxduring load. With Actuator and Micrometer, the metric istomcat.threads.busycompared withtomcat.threads.config.max. - Latency grows while CPU use stays low. Queued requests wait for threads, and the CPU has no work to do.
- Thread dumps show most worker threads parked in socket reads or connection pool waits.
If busy threads stay well below the maximum, the pool is not limiting you and the switch will change little.
Is the work mostly waiting?
Compare CPU use to latency under load. If CPU is at 15% while the pool is full, the threads are waiting. If CPU is at 90%, adding concurrency only adds contention.
Is a downstream resource the real limit?
Spring Boot's default HikariCP pool has 10 connections. If every request needs a connection, 10 requests run the database part at a time, no matter how many threads exist. Thousands of virtual threads then queue on the pool, and the pool timeout (30 seconds by default) can start producing errors. The fix is to size the pool and cap concurrency deliberately, not to avoid virtual threads.
Common errors in judging fit
- Expecting faster single requests. A benchmark that sends one request at a time shows no gain, and that is the correct result. Measure under concurrent load that exceeds the old pool size.
- Testing with no real blocking. A synthetic endpoint that returns a constant string never waits, so it cannot show the effect. Use realistic calls or a sleep.
- Moving CPU-heavy work to virtual threads to speed it up. Parallelism stays bounded by cores. If you need more CPU parallelism, use a pool sized to the core count, or add machines.
- Pooling virtual threads. Do not wrap virtual threads in a fixed-size pool to "control" them. They are cheap, so create one per task. Limit concurrency with a
Semaphoreor a connection pool instead. - Treating the switch as free for all code. Libraries that block inside
synchronized, or code that stores large objects inThreadLocalvariables, can behave worse. Later chapters cover both. - Ignoring mixed workloads. A service with mostly I/O endpoints and one CPU-heavy endpoint can still benefit overall. But the CPU-heavy endpoint can now take more of the cores, because more requests run at once. Watch its effect on the other endpoints, and consider limiting it.
Measuring the result
Treat the change as an experiment with one variable:
- Record a baseline under load: requests per second, p50 and p99 latency, CPU, busy threads, connection pool waits.
- Set
spring.threads.virtual.enabled=trueand repeat the same load test. - Compare. A good result is higher throughput or lower p99 latency at the same load, with CPU and pool usage still in safe ranges.
- If nothing changes, the bottleneck is not threads. That tells you where to look next.
Exercise
A Spring MVC service handles 500 requests per second. Each request takes about 200 ms, nearly all of it waiting on a JDBC query. Tomcat is configured with 200 worker threads. Using Little's law, how many requests are in flight on average, and would virtual threads likely raise throughput?
Show answer
In-flight requests = 500 × 0.2 s = 100. That is below the 200-thread limit, so the pool is not saturated and virtual threads would change little at this load. They would matter if traffic grew past about 1,000 requests per second (200 threads ÷ 0.2 s), where the pool becomes the limit. Even then, the database connection pool (10 connections by default in HikariCP) must be sized to handle the extra concurrency.
Exercise
A team enables virtual threads for a service that renders large PDF reports using CPU-heavy code on an 8-core server. Throughput does not improve. Why, and what should they do instead?
Show answer
The work is CPU-bound, so there is no blocked time for virtual threads to hide. Carrier threads default to the number of cores, and the operating system gives platform threads the same limit. To raise throughput, they should reduce the CPU cost per report, use a pool sized to the core count to keep concurrency bounded, or add CPU capacity.