Scaling I/O-Bound Java Services with Java 21 Virtual Threads
Java 21 virtual threads can raise concurrency for I/O-bound services, but success depends on avoiding carrier-thread pinning and matching the executor to your workload.
24 Oct 2025, 12:28 UTC

Problem and takeaway
Your Java service receives a burst of requests. Each request calls a slow external API or waits on a database query, and each request is assigned its own platform thread. The thread pool fills up. New requests queue or fail, even though the CPU is mostly idle because the threads are blocked waiting for network responses. Java 21 virtual threads (JEP 444) address this by offering JVM-managed threads that are cheap to create and that unmount from a carrier thread when they block. The practical takeaway: for I/O-bound request handling, replacing a fixed platform-thread pool with a virtual-thread executor can let you handle far more concurrent requests without rewriting your application logic.
How virtual threads differ from platform threads
A platform thread maps one-to-one to an operating system thread. Creating thousands of them consumes memory and kernel scheduling resources. A virtual thread is scheduled by the JVM instead. When a virtual thread performs a blocking I/O operation, it parks and its carrier thread is freed to run another virtual thread. This unmounting behavior means you can run millions of virtual threads on a small pool of carrier threads, limited by memory and file descriptors rather than OS thread limits.
Virtual threads are not faster for CPU-bound work. A tight calculation still consumes carrier-thread time. If you schedule millions of compute-heavy virtual threads, the JVM can spend more time scheduling than executing. Keep CPU-intensive tasks on platform threads or a dedicated executor.
Migration mechanics and concrete configuration
The simplest migration point is the executor used by your request handler. Replace a fixed pool with the virtual-thread variant:
// Before: platform-thread pool
ExecutorService pool = Executors.newFixedThreadPool(20);
// After: virtual thread per task
ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor();
Run this on JDK 21 or later (OpenJDK, Oracle JDK, or another TCK-compatible build). Required permissions: none beyond normal JVM startup. Replace 20 with your current pool size; the virtual-thread executor ignores pool-size arguments because it creates a thread per task. Expected checks: after redeploy, watch request throughput and average latency under load. Relevant risk: if request handlers perform heavy computation, virtual threads can oversubscribe the carrier pool, whose default size equals the number of available processors.
In a Spring Boot application, you can expose the executor as a bean so Tomcat or Jetty uses it:
@Bean
Executor taskExecutor() {
return Executors.newVirtualThreadPerTaskExecutor();
}
Where to run: in your application configuration class, compiled with JDK 21 and launched with a Java 21 runtime. Verify the runtime version with java -version before deploying.
Pinning, synchronized blocks, and library compatibility
When a virtual thread enters a synchronized block or a native method and then blocks, it can pin the carrier thread. The carrier stays occupied and cannot run other virtual threads, reducing the benefit of the migration. Prefer java.util.concurrent.locks.ReentrantLock with tryLock or park-based waiting for code paths that block on I/O.
Thread identity is another trap. Code that stores request-scoped data in ThreadLocal, or that compares Thread.currentThread().getId() to route work, may behave unexpectedly because virtual threads are recycled. Structured concurrency (JEP 453, preview in Java 21) and scoped values provide safer alternatives by tying data to a task lifecycle instead of a thread.
Audit third-party dependencies for heavy synchronized usage or ThreadLocal caches before rolling virtual threads out to all traffic. A library that pools connections by thread ID may break or leak when virtual threads are reused across requests.
Verification: benchmarks and diagnostics
Do not assume virtual threads will improve your service. Measure against your baseline. A concrete comparison: run an endpoint that makes three sequential HTTP calls to a slow upstream. Test with newFixedThreadPool(16) and with newVirtualThreadPerTaskExecutor(), then use a load tool such as wrk or ab to record requests per second and median latency. Run the test on a staging environment with production-like traffic patterns.
To detect pinning, enable Java Flight Recorder and look for jdk.VirtualThreadPinned events. A high count means synchronized blocks or native calls are keeping carrier threads busy. You can also run jcmd <pid> Thread.print and check whether carrier threads show long runtimes while virtual threads are parked. Replace <pid> with the JVM process ID.
For memory footprint, compare GC logs between the two executors. Virtual threads reduce per-thread stack memory, but they may increase allocation rates. Watch for garbage-collection pauses that correlate with bursts of virtual-thread creation.
Practical check and limitation
Set up a canary deployment with a small percentage of production traffic. Capture throughput, latency, error rates, and CPU usage for at least 15 to 30 minutes. Compare against the platform-thread baseline. If throughput rises and latency stays flat or drops, the migration is likely a win. If CPU usage climbs without a request-rate gain, your workload may be compute-bound, and you should keep those handlers on a fixed platform-thread pool.
Virtual threads do not remove the need for connection pooling, backpressure, or timeouts. They raise the concurrency ceiling for waiting tasks, but downstream services and databases still have their own limits.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.