Java 21 (September 2023) made virtual threads a final feature (JEP 444). Spring Boot 3.2 (November 2023) added one property to use them. I am moving a small service to Java 21 and Boot 3.2 anyway, so I read up on what can go wrong if I also set that property.
For a typical blocking web service that waits on databases and HTTP calls, I think it is worth testing. It does not make anything faster by itself, though, and there are a few traps.
What virtual threads change
A platform thread is a wrapper around an OS thread. It is expensive: about 1 MB of stack reserved by default, and the OS schedules it. So servers use a pool, for example Tomcat’s default of 200 threads. When all 200 threads are blocked on I/O, request 201 waits, even if the CPU is idle.
A virtual thread is managed by the JVM. When it blocks on I/O, the JVM unmounts it from its carrier (an OS thread) and runs another virtual thread on that carrier. You can have hundreds of thousands of them. Blocking becomes cheap again.
The result: you can keep the simple, blocking programming style (RestClient, JDBC, Thread.sleep) and still handle many concurrent requests that mostly wait.
When it helps
It helps when you have many concurrent requests that each wait on I/O: more requests in flight with the same memory. It does not help CPU-bound work like image processing or heavy JSON, because there you are limited by cores. A low-traffic service will see no change. An app written with WebFlux already avoids blocking, so there is little reason to switch.
The case people forget: if the bottleneck is a downstream system, for example a database that allows 20 connections, virtual threads only move the queue. They remove the thread limit, not the connection limit.
Turn it on
You need Java 21 and Spring Boot 3.2 or newer.
# application.properties
spring.threads.virtual.enabled=true
With this property, Spring Boot:
- runs each Tomcat (or Jetty) request on a new virtual thread,
- configures the application task executor (
@Async,applicationTaskExecutor) to use virtual threads, - uses virtual threads for
@Scheduledtasks, - uses them in some messaging listener containers (for example RabbitMQ and Kafka).
Check that it works. Log the current thread in a controller:
@RestController
class PingController {
@GetMapping("/ping")
String ping() {
return Thread.currentThread().toString();
}
}
The response should look like VirtualThread[#52]/runnable@ForkJoinPool-1-worker-3. If you see http-nio-8080-exec-1, the property is not active, or you run on an older Java.
A realistic endpoint
A typical case is an endpoint that calls a slow downstream service:
@RestController
class QuoteController {
private final RestClient client;
QuoteController(RestClient.Builder builder) {
this.client = builder.baseUrl("http://quotes.internal.example.com").build();
}
@GetMapping("/quote/{id}")
Quote quote(@PathVariable String id) {
// Blocking call. On a virtual thread, the carrier is released while we wait.
return client.get().uri("/quotes/{id}", id).retrieve().body(Quote.class);
}
}
record Quote(String id, String text) {}
With platform threads and a 200-thread pool, 200 slow downstream calls fill the pool. With virtual threads, the service can keep accepting requests. Now the downstream service and your timeouts become the limit, which is where it should be.
This also means you need timeouts. With platform threads, the full pool was an accidental back-pressure. Without it, a hanging downstream can collect thousands of waiting requests. Every HTTP client needs a connect and read timeout.
Pitfall 1: pinning
In Java 21, a virtual thread cannot unmount while it is inside a synchronized block or method. If it blocks on I/O there, it holds its carrier thread. This is called pinning. There are only as many carriers as CPU cores by default, so a few pinned threads can stall the whole app.
Code that pins:
private final Object lock = new Object();
void refresh() {
synchronized (lock) {
callRemoteService(); // blocking I/O while holding a monitor -> pinned
}
}
Fix: use a ReentrantLock. Virtual threads can unmount while waiting on it.
private final ReentrantLock lock = new ReentrantLock();
void refresh() {
lock.lock();
try {
callRemoteService();
} finally {
lock.unlock();
}
}
Short synchronized blocks that do no I/O are fine. Do not rewrite every synchronized keyword. Find the ones that block.
To find pinning, start the JVM with:
java -Djdk.tracePinnedThreads=full -jar app.jar
The JVM prints a stack trace when a virtual thread blocks while pinned. You can also record the JFR event jdk.VirtualThreadPinned:
java -XX:StartFlightRecording=filename=rec.jfr,settings=profile -jar app.jar
jfr print --events jdk.VirtualThreadPinned rec.jfr
Pinning can also come from libraries: older JDBC drivers, connection pools, or caches that use synchronized around I/O. Check the release notes of your drivers for virtual thread support and update them before you enable the property in production.
Pitfall 2: the connection pool is now the queue
HikariCP’s default maximumPoolSize is 10. With 200 platform threads, at most 200 requests compete for those 10 connections. With virtual threads, 5000 requests can compete. They wait inside Hikari, and after connectionTimeout (30 seconds by default) they fail.
What to do:
- Size the pool for what the database can handle, not for the number of threads.
- Lower
connectionTimeoutso requests fail fast instead of piling up. - Limit concurrency explicitly where you call a scarce resource:
private final Semaphore dbPermits = new Semaphore(20);
Report loadReport(long id) throws InterruptedException {
dbPermits.acquire();
try {
return repository.load(id);
} finally {
dbPermits.release();
}
}
A Semaphore is the natural tool with virtual threads. Do not create a fixed pool of virtual threads to limit concurrency. Virtual threads are meant to be created per task and thrown away.
Pitfall 3: ThreadLocal caches
Some code caches expensive objects in a ThreadLocal, assuming a few hundred long-lived threads. With one virtual thread per request, every request creates a new copy, and the cache does nothing except use memory. Look for ThreadLocal holding things like SimpleDateFormat, buffers or parsers. Replace them with thread-safe objects (DateTimeFormatter) or a real object pool.
ThreadLocal for request context (security context, MDC logging) still works. Each virtual thread has its own value.
Pitfall 4: CPU-heavy work on virtual threads
Virtual threads are scheduled on a small ForkJoinPool. A long CPU loop on a virtual thread keeps a carrier busy, and there is no time slicing. For CPU-heavy work, use a normal bounded executor with platform threads, sized to the number of cores.
Using them without Spring
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> results = urls.stream()
.map(url -> executor.submit(() -> fetch(url)))
.toList();
for (var f : results) {
System.out.println(f.get());
}
}
Thread.ofVirtual().start(runnable) also works for single tasks. Structured concurrency (StructuredTaskScope) is still a preview API in Java 21, so I do not use it in production code yet.
How I plan to test it
I have no numbers yet. This is the plan for my service:
- Run a load test with a realistic mix of endpoints, with the property off. Record throughput, p99 latency, heap and CPU.
- Turn it on. Run the same test.
- Run with
-Djdk.tracePinnedThreads=fullin a test environment and read the output. - Watch the connection pool metrics (
hikaricp_connections_pendingin Micrometer) during the test.
If the service was limited by Tomcat threads, there should be a difference. If it was limited by the database or by CPU, there will not be one.