Video in progress
How do you enable virtual threads in Spring Boot 3.2+, and what should you watch out for?
spring.threads.virtual.enabled=true (Java 21+) — Tomcat runs requests, @Async and scheduler tasks on virtual threads. Throughput goes up in apps with lots of blocking I/O, but you need to watch for pinning, unbounded concurrency and ThreadLocal.
📖 Answer
spring:
threads:
virtual:
enabled: true
What you gain: a cheap virtual thread per request. A thread waiting on the database or an external API doesn't hold a platform thread, so the 200 Tomcat thread ceiling goes away.
What to watch:
-
The limit now moves to your resources. Before, 200 threads were a natural limit on their own. Now 5000 requests come in at once and pile up on a Hikari pool with 20 connections —
connection-timeouterrors. Protect the downstream resources: pool, semaphore, rate limit. -
Pinning. In Java 21–23, blocking I/O inside a
synchronizedblock "pins" the virtual thread to its carrier thread. If you have a lot of those spots, throughput drops. To find them:-Djdk.tracePinnedThreads=full(21–23). In Java 24 (JEP 491) this is mostly fixed forsynchronized. On older versions, useReentrantLockin the hot spots. -
ThreadLocal. Virtual threads are many and short-lived — caching big objects in a ThreadLocal (for example,
SimpleDateFormat) is pointless and eats memory. -
CPU-heavy work doesn't get faster — virtual threads only make waiting cheap.
Run a load test before and after enabling it, and compare latency percentiles and pool wait metrics.
Sign up to mark studied questions and save your progress.