Video in progress
If you enable Java 21 virtual threads in a service, what changes in calls between services, and what should you watch out for?
With spring.threads.virtual.enabled=true each request runs on a virtual thread, and blocking HTTP/JDBC calls don't tie up a platform thread, so Tomcat's 200-thread limit goes away. But if the resources below aren't limited (the DB pool, the downstream service), you can now overwhelm them.
📖 Answer
Before, there was a natural "limiter": the 200 Tomcat threads. If the downstream slowed down, the threads ran out and the service stopped accepting requests, which was bad, but it pushed the load back upward. With virtual threads, even 10,000 parallel requests can "wait" comfortably. The consequences:
- 5,000 virtual threads queue up for a 20-connection HikariCP pool, and after
connectionTimeoutyou get mass errors; - the downstream service gets 10 times more parallel requests than before, and it falls over;
- memory: a virtual thread is cheap, but each request's buffers and objects are not.
So you need to limit parallelism explicitly, with a bulkhead (semaphore) or pool sizes:
private final Semaphore paymentLimit = new Semaphore(50);
PaymentDto charge(ChargeRequest r) throws InterruptedException {
if (!paymentLimit.tryAcquire(200, TimeUnit.MILLISECONDS)) {
throw new ServiceBusyException(); // 503
}
try {
return paymentClient.charge(r);
} finally {
paymentLimit.release();
}
}
The second trap is pinning. In Java 21, if a virtual thread blocks inside a synchronized block, it also holds on to its carrier thread. Some older libraries (old JDBC drivers, some HTTP clients) have such code. In Java 21 you find it with -Djdk.tracePinnedThreads=full or the jdk.VirtualThreadPinned event in JFR. In Java 24 (JEP 491) pinning because of synchronized is largely gone, which is a good reason to move to Java 25 LTS.
The third is the habit of putting a big cache in a ThreadLocal. Each virtual thread gets its own copy, and there can be millions of them.
And a reminder: virtual threads don't reduce latency, they only free up resources while waiting. If the downstream answers in 2 seconds, the request still takes 2 seconds.
Sign up to mark studied questions and save your progress.