Virtual threads in Spring Boot 4 — what to check before you flip the switch
One property, spring.threads.virtual.enabled=true, moves Tomcat request handling, @Async and @Scheduled onto virtual threads. But once threads are cheap, the queue moves to your HikariCP pool and your downstream services. Here is what Java 25 fixed about pinning, what still pins, how to size the pool, how to bound concurrency with a Semaphore, and how to find pinning with JFR.
- Spring Boot
- 4.2.0
- Java
- 25 LTS
- Config
- 1 line
- Carrier threads
- CPU cores
One line turns it on
spring:
threads:
virtual:
enabled: true
That is the whole setup. It works on Java 21 or later, and the reference documentation strongly recommends Java 24 or later. The pinning section below explains why. Spring Boot 4.2.0 supports Java 17 through 25, so if you are already on Java 25, one line is all that is left.
sequenceDiagram
participant C as Client
participant T as Tomcat (connector)
participant V as Virtual thread (one per request)
participant P as Carrier platform thread
participant D as DB / remote API
C->>T: HTTP request
T->>V: Hand the request to a new virtual thread
V->>P: Mount and run
V->>D: Query (I/O wait)
Note over V,P: While waiting, V unmounts<br/>and P runs another request
D-->>V: Response
V->>P: Remount and finish
V-->>C: HTTP response
The key step is the note in the middle: a waiting request does not hold an OS thread. That is how a server that used to survive on 200 platform threads can hold thousands of concurrent requests on the same hardware.
What actually changes
The property changes the threads Spring Boot creates for you. Per the 4.2 reference documentation:
| What | Before | After |
|---|---|---|
| Tomcat request handling | http-nio-8080-exec-N pool (200 max by default) |
A virtual thread per request |
@Async applicationTaskExecutor |
ThreadPoolTaskExecutor |
SimpleAsyncTaskExecutor on virtual threads |
@Scheduled taskScheduler |
ThreadPoolTaskScheduler |
SimpleAsyncTaskScheduler |
MVC async requests, GraphQL Callable, WebSocket channels, JPA bootstrap |
Same executors | Same virtual-thread executors |
flowchart LR
A["spring.threads.virtual.enabled=true"] --> B["Tomcat request threads"]
A --> C["applicationTaskExecutor<br/>@Async · MVC async · JPA bootstrap"]
A --> D["taskScheduler<br/>@Scheduled"]
E["Your own ExecutorService"] -.->|"unchanged"| F["Platform threads"]
G["Pools created by libraries"] -.->|"unchanged"| F
Those two dotted lines are the trap. A ThreadPoolTaskExecutor you declared as a @Bean, and pools inside third-party libraries, do not change. If a thread dump still shows pool-1-thread-3 after you “enabled virtual threads”, this is usually why.
Cheap threads move the bottleneck
Virtual threads are not free, they are cheap. You made the receiving end cheap, so the queue now forms behind it.
flowchart LR
R["5,000 concurrent requests"] --> T["Tomcat<br/>5,000 virtual threads"]
T --> H["HikariCP<br/>10 connections"]
H --> DB[("PostgreSQL")]
T --> A["Remote API<br/>50 requests/sec limit"]
| Resource | Default | Where it is set |
|---|---|---|
| Connections Tomcat accepts | max-connections 8,192 / accept-count 100 |
server.tomcat.* |
| JDBC connections | HikariCP maximumPoolSize 10, connectionTimeout 30s |
spring.datasource.hikari.* |
| HTTP client connections | Differs per library | Each client’s config |
| Downstream capacity | The other service’s rate limit | Their side |
The smallest number in that table is your real concurrency ceiling. With the HikariCP default of 10, 5,000 virtual threads still produce at most 10 simultaneous queries. The other 4,990 park while waiting for a connection. Memory holds up, but response time grows with the queue.
The usual reflex is wrong here. “5,000 concurrent requests, so let’s raise the pool to 500.” The HikariCP guidance has said the opposite for years:
- Every connection costs the database server memory, lock contention and context switches. A small pool, saturated, with the rest waiting usually delivers higher throughput.
- Start near
cores × 2 + effective spindlesand tighten it with measurements. A 4-core server lands around 10. - Grow the pool only as far as the database can take it. Growing it for the application’s sake kills the database first.
Three ways to shorten the wait
1. Cap how long you wait for a connection
spring:
datasource:
hikari:
maximum-pool-size: 10 # what the DB can sustain
connection-timeout: 3000 # fail in 3s, not 30s
leak-detection-threshold: 20000
Waiting 30 seconds and then failing means the user loses 30 seconds and gets a 500 anyway, while the virtual thread and the Tomcat connection stay pinned for those 30 seconds. Fail fast and make the failure visible.
2. Bound concurrency with a Semaphore, not a thread pool
Never pool virtual threads. If you need to limit how many run at once, put a Semaphore directly in front of the scarce resource.
@Component
public class ReportClient {
private final Semaphore permits = new Semaphore(20); // what the remote API can take
private final RestClient restClient;
public ReportClient(RestClient.Builder builder) {
this.restClient = builder.baseUrl("https://reports.example.com").build();
}
public Report fetch(long id) {
if (!permits.tryAcquire(Duration.ofMillis(500))) {
throw new ReportBusyException(id); // reject instead of queueing
}
try {
return restClient.get().uri("/reports/{id}", id).retrieve().body(Report.class);
} finally {
permits.release();
}
}
}
Passing a timeout to tryAcquire is the point. acquire() with no bound turns “no thread pool” into an unbounded queue. And do not stack another semaphore on top of a pool that is already one, such as HikariCP.
For @Async, Spring Boot gives you a setting:
spring:
task:
execution:
simple:
concurrency-limit: 32 # cap for the virtual-thread executor
3. Time out every outbound call
spring:
http:
clients:
connect-timeout: 1s
read-timeout: 3s
Without timeouts, one slow downstream holds semaphore permits and connections forever. Virtual threads make that wait cheap, not finite.
Pinning: Java 24 closed the synchronized case
A virtual thread is pinned when it cannot unmount from its carrier while blocked. On Java 21, blocking on I/O inside a synchronized block always pinned, which is where the “replace every synchronized with ReentrantLock” advice came from. JEP 491 in JDK 24 removed that cause, and Java 25 inherits the fix.
| JDK | Blocking inside synchronized |
Object.wait() |
Native (JNI/FFM) frames |
|---|---|---|---|
| 21 (LTS) | Pins | Pins | Pins |
| 22 · 23 | Pins | Pins | Pins |
| 24 | No pin | No pin | Pins |
| 25 (LTS) | No pin | No pin | Pins |
flowchart LR
A["Blocking call"] --> B{"Where does it block?"}
B -->|"synchronized · Object.wait"| C["JDK 24+<br/>releases the carrier"]
B -->|"inside native code"| D["Still pins<br/>check with JFR"]
B -->|"static initializer"| D
So on Java 25, do not mechanically rewrite synchronized blocks. Rewriting battle-tested synchronization to ReentrantLock without a proper finally is a worse risk than the pinning you are avoiding. synchronized inside libraries (JPA providers, JDBC drivers, cache clients) is fine too.
What still pins is narrow:
- Native frames: C code entered through JNI or FFM that calls back into Java and blocks.
- Class initialization: blocking inside a
static { }block.
Both tend to come from libraries rather than your code. If you suspect them, use JFR. -Djdk.tracePinnedThreads was removed in JDK 24, so that option from older blog posts now does nothing.
# Record for 60 seconds
jcmd <pid> JFR.start name=pinning settings=profile duration=60s filename=pinning.jfr
# Print just the pinning events (20 ms threshold by default)
jfr print --events jdk.VirtualThreadPinned pinning.jfr
A hit shows the native frame or class initializer right in the stack. The carrier count defaults to the number of CPU cores and can be tuned with jdk.virtualThreadScheduler.parallelism, but removing the pin comes first.
MDC and ThreadLocal
Because one request owns one virtual thread from start to finish, request-scoped ThreadLocal works as before. Logback’s MDC is a ThreadLocal, so your traceId still shows up in request logs.
What changes is the habit of caching expensive things per thread.
// Fine: a value used within the request
MDC.put("traceId", traceId);
// Risky: per-thread caches that used to be reused
private static final ThreadLocal<ByteBuffer> BUFFER =
ThreadLocal.withInitial(() -> ByteBuffer.allocateDirect(1024 * 1024));
The second one costs 200 MB with 200 platform threads. With virtual threads there is a new thread per task, so you allocate one buffer per request. This is exactly the case JEP 444 warns about; move such caches into a pool or an ordinary cache.
MDC does not follow you into @Async automatically. Attach a TaskDecorator to the executor.
@Bean
AsyncTaskExecutor applicationTaskExecutor(SimpleAsyncTaskExecutorBuilder builder) {
return builder.taskDecorator(runnable -> {
Map<String, String> context = MDC.getCopyOfContextMap();
return () -> {
if (context != null) MDC.setContextMap(context);
try {
runnable.run();
} finally {
MDC.clear();
}
};
}).build();
}
There is a better carrier for context now too. ScopedValue (JEP 506) is final in JDK 25. It binds an immutable value to a scope and releases it when the block exits. Note that Structured Concurrency is still a preview in JDK 25 (JEP 505), so it needs --enable-preview.
Measure before, measure after
Virtual threads pay off when the thread pool was the bottleneck. If the database or a downstream API was already the limit, throughput stays flat and only the queue gets longer. Check two things first:
- Is the Tomcat pool regularly full? (in-flight requests versus pool size)
- Which downstream saturates first? (pool sizes and timeouts)
After enabling, compare the same load with this table.
| What to watch | Why |
|---|---|
| In-flight requests | Actual concurrent work |
| Hikari active / pending | Whether connection waits grew |
| p99 latency | Whether queueing became latency |
| CPU, GC | The price of more threads |
jdk.VirtualThreadPinned events |
Whether pinning is eating throughput |
Confirming it is really on takes one endpoint that reports the handling thread.
@GetMapping("/thread")
Map<String, Object> thread() {
Thread t = Thread.currentThread();
return Map.of("virtual", t.isVirtual(), "name", t.getName());
}
{"virtual": true, "name": "tomcat-handler-0"}
Pin that in a test, and the day someone slips in a custom Executor that disables the setting, you will know.
@SpringBootTest(webEnvironment = RANDOM_PORT)
class ThreadModeTest {
@LocalServerPort
int port;
@Test
void requestsRunOnVirtualThreads() {
Map<?, ?> body = RestClient.create()
.get().uri("http://localhost:" + port + "/thread")
.retrieve().body(Map.class);
assertThat(body.get("virtual")).isEqualTo(true);
}
}
Things that bite
- An app with only
@Scheduledexits right after startup. Virtual threads are daemon threads, and a JVM exits when only daemons remain. The documented fix isspring.main.keep-alive=true. - You keep tuning thread-pool properties.
server.tomcat.threads.maxandspring.task.execution.pool.*have no effect once virtual threads are on; there is no pool. Usespring.task.execution.simple.concurrency-limitinstead. - Your own executors stay as they are.
new ThreadPoolTaskExecutor()still runs platform threads. Replace it withExecutors.newVirtualThreadPerTaskExecutor(). - You expect CPU-bound work to speed up. Encryption, large JSON serialization, image processing: carriers equal cores, so nothing gets faster. Long CPU work also blocks other requests by holding a carrier.
- You forget Tomcat’s own limits.
max-connectionsandaccept-countstill apply, independently of threads. - You raise the connection pool to match traffic. More concurrent requests do not mean more database capacity. Size the pool for the database and reject the excess with a semaphore.
Wrap-up
flowchart LR
A["Java 25 + Boot 4.2"] --> B["spring.threads.virtual.enabled=true"]
B --> C["Tidy thread-pool properties<br/>check keep-alive"]
C --> D["Fix limits: Hikari,<br/>HTTP timeouts, Semaphore"]
D --> E["Same load before/after<br/>check pinning in JFR"]
- One line enables it, and on Java 24 or later you can stop worrying about the
synchronizedpinning story. - The gain appears where the thread pool was the bottleneck. The bottleneck moves to HikariCP and your downstreams, so set those ceilings first.
- Bound concurrency with a
Semaphore, a short connection timeout and outbound timeouts, not with a thread pool. - Remember the daemon-thread exit, the executors that do not change, and the CPU-bound case, and production will hold fewer surprises.
Comments