Video in progress

Strong Middle 🌱 Spring

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:

  1. 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-timeout errors. Protect the downstream resources: pool, semaphore, rate limit.

  2. Pinning. In Java 21–23, blocking I/O inside a synchronized block "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 for synchronized. On older versions, use ReentrantLock in the hot spots.

  3. ThreadLocal. Virtual threads are many and short-lived — caching big objects in a ThreadLocal (for example, SimpleDateFormat) is pointless and eats memory.

  4. 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.