Virtual Threads in Spring Boot: Configuration, Pitfalls and Monitoring
Turning on virtual threads in Spring Boot with spring.threads.virtual.enabled: what moves to virtual threads (Tomcat, @Async, @Scheduled, HTTP clients) and what doesn't. A measured before-and-after run, manual setup for older versions, and the pitfalls: keep-alive, lost limits, pinning, monitoring.
kvi5hnuCode Sprout team member9 min readOn this page
Spring MVC has always been thread-per-request: Tomcat takes a worker thread from a pool of 200, and that thread runs the controller, the service calls and the JDBC queries until the response is written. Under heavy I/O-bound load, the pool runs dry while its threads sit waiting, exactly the problem from Part 1. Spring's earlier remedies, @Async and TaskExecutor, only moved the waiting to another bounded pool.
Since Spring Boot 3.2 (November 2023, on Spring Framework 6.1), one property moves this whole model to virtual threads:
spring.threads.virtual.enabled=true
It requires Java 21 or later, and the Spring Boot documentation strongly recommends Java 24 or later, because synchronized no longer pins there (article 13).
What the property changes

- The embedded web server. Tomcat's request processing runs on a virtual thread per request, named
tomcat-handler-N. Jetty is given a virtual-thread executor too.server.tomcat.threads.maxthen has no effect, as its own description says. applicationTaskExecutor. When you haven't defined anExecutorbean, Boot auto-configures aSimpleAsyncTaskExecutorthat starts a virtual thread per task, instead of aThreadPoolTaskExecutor. It runs@Asyncmethods,Callableand other asynchronous return values of MVC controllers, and WebFlux's blocking execution support.taskScheduler.@Scheduledmethods run on aSimpleAsyncTaskSchedulerwith virtual threads, which ignores pool-size properties.- HTTP clients. Since Spring Boot 4.0, auto-configured HTTP clients backed by the JDK
HttpClientuse virtual threads too. - Builders. The
SimpleAsyncTaskExecutorBuilderandSimpleAsyncTaskSchedulerBuilderbeans produce virtual-thread executors, so executors you build with them follow the property.
Before and after
This application has one endpoint that waits 200 ms for a slow downstream call and then calls an @Async service. It also has one @Scheduled job. The program starts it twice, without and with virtual threads, and both times Tomcat is limited to 20 worker threads. Each time it fires 200 concurrent requests. It was run on Spring Boot 3.5.0 and Java 25, and needs spring-boot-starter-web.
package trip;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.context.WebServerApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableAsync
@EnableScheduling
public class QuoteApp {
static final Set<String> requestThreads = ConcurrentHashMap.newKeySet();
static final CountDownLatch scheduledRan = new CountDownLatch(1);
static volatile String scheduledThread;
static volatile String asyncThread;
@Service
public static class HotelService {
@Async // runs on the applicationTaskExecutor
public CompletableFuture<Integer> hotel(String city) throws InterruptedException {
asyncThread = describe(Thread.currentThread());
Thread.sleep(50);
return CompletableFuture.completedFuture(95);
}
}
@RestController
public static class QuoteController {
@Autowired HotelService hotels;
@GetMapping("/quote")
public String quote(@RequestParam String route) throws Exception {
requestThreads.add(describe(Thread.currentThread()));
Thread.sleep(200); // a slow, blocking downstream call
int flight = 100 + route.chars().sum() % 400;
return route + " " + (flight + 3 * hotels.hotel("Oslo").get());
}
}
@Service
public static class Refresher {
@Scheduled(fixedDelay = 60_000)
public void refreshFares() {
scheduledThread = describe(Thread.currentThread()) + " (daemon: " + Thread.currentThread().isDaemon() + ")";
scheduledRan.countDown();
}
}
static String describe(Thread t) {
String name = t.getName().replaceAll("\\d+$", "N"); // tomcat-handler-17 -> tomcat-handler-N
return (t.isVirtual() ? "virtual " : "platform ") + name;
}
static long run(boolean virtual) throws Exception {
requestThreads.clear();
ConfigurableApplicationContext ctx = new SpringApplication(QuoteApp.class).run(
"--spring.threads.virtual.enabled=" + virtual,
"--server.port=0",
"--server.tomcat.threads.max=20", // ignored when virtual threads are enabled
"--spring.main.banner-mode=off",
"--logging.level.root=warn",
"--logging.level.org.apache.tomcat.util.net=off"); // hide the acceptor's shutdown noise
try {
int port = ((WebServerApplicationContext) ctx).getWebServer().getPort();
scheduledRan.await();
HttpClient client = HttpClient.newHttpClient();
long start = System.nanoTime();
List<Future<String>> replies = new ArrayList<>();
try (var callers = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 200; i++) {
replies.add(callers.submit(() -> client.send(
HttpRequest.newBuilder(URI.create("http://localhost:" + port + "/quote?route=LIS-OSL")).build(),
HttpResponse.BodyHandlers.ofString()).body()));
}
}
long millis = (System.nanoTime() - start) / 1_000_000;
long ok = replies.stream().filter(f -> f.resultNow().equals("LIS-OSL 500")).count();
String executor = ctx.getBean("applicationTaskExecutor").getClass().getSimpleName();
System.out.println("virtual threads " + (virtual ? "on:" : "off:"));
System.out.println(" 200 requests of 200 ms, correct replies: " + ok + ", total time "
+ (millis < 1_000 ? "under 1 s" : millis > 1_800 ? "over 1.8 s" : "between 1 and 1.8 s"));
System.out.println(" request threads: " + requestThreads);
System.out.println(" @Async ran on: " + asyncThread);
System.out.println(" @Scheduled ran on: " + scheduledThread);
System.out.println(" applicationTaskExecutor: " + executor);
return millis;
} finally {
ctx.close();
}
}
public static void main(String[] args) throws Exception {
run(false);
run(true);
}
}
Output:
virtual threads off:
200 requests of 200 ms, correct replies: 200, total time over 1.8 s
request threads: [platform http-nio-auto-1-exec-N]
@Async ran on: platform task-N
@Scheduled ran on: platform scheduling-N (daemon: false)
applicationTaskExecutor: ThreadPoolTaskExecutor
virtual threads on:
200 requests of 200 ms, correct replies: 200, total time under 1 s
request threads: [virtual tomcat-handler-N]
@Async ran on: virtual task-N
@Scheduled ran on: virtual scheduling-N (daemon: true)
applicationTaskExecutor: SimpleAsyncTaskExecutor
- Without virtual threads, 20 Tomcat workers served the 200 requests in about 10 waves, each the 200 ms wait plus the
@Asynccalls queueing for the default 8-thread task pool, so the run took well over 1.8 seconds.@Asyncused the pooledThreadPoolTaskExecutor(task-N), and the scheduler thread was a non-daemon platform thread. - With virtual threads, every request got its own virtual thread,
server.tomcat.threads.max=20was ignored, and all 200 requests waited at the same time: well under a second.@Asyncand@Scheduledmoved to virtual threads too. No application code changed. - The scheduler thread is now a daemon thread. That matters, as the first pitfall below shows.
Older versions and manual setup
On Spring Boot 3.0 or 3.1, or to control exactly which parts move, define the beans yourself. Naming the executor bean applicationTaskExecutor makes @Async and async MVC use it:
import java.util.concurrent.Executors;
import org.springframework.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
@Configuration(proxyBeanMethods = false)
public class VirtualThreadConfig {
@Bean(name = "applicationTaskExecutor")
AsyncTaskExecutor applicationTaskExecutor() {
// TaskExecutorAdapter makes a JDK executor usable wherever Spring expects an AsyncTaskExecutor
return new TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor());
}
@Bean
TomcatProtocolHandlerCustomizer<?> virtualThreadRequests() {
return handler -> handler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
}
}
On Boot 3.2 and later, prefer the property. It also covers the scheduler and WebFlux, names threads consistently, and lets Boot manage the executors' lifecycle. If you need a custom executor on 3.2+, build it from the injected SimpleAsyncTaskExecutorBuilder, so that it follows the property. Remember that any Executor bean you define replaces the auto-configured one: a ThreadPoolTaskExecutor bean you defined years ago keeps @Async on platform threads, whatever the property says.
Pitfalls
1. The application exits by itself
Virtual threads are always daemon threads, and the JVM exits when only daemon threads remain. An application whose only work is @Scheduled jobs, or a message listener that runs on virtual threads, may start, run nothing that holds the JVM, and exit. Set:
spring.main.keep-alive=true
Web applications are usually kept alive by the server's own non-daemon threads, but the setting is cheap insurance.
2. The limits you relied on are gone
A pool of 200 Tomcat threads was also an implicit concurrency limit: never more than 200 requests in the application at once. With virtual threads, up to server.tomcat.max-connections (8,192 by default) requests run at the same time. They then queue up at the next limit:
- The JDBC connection pool. HikariCP's default
maximum-pool-sizeis 10. With 2,000 concurrent requests, 1,990 wait for a connection and time out afterconnection-timeout(30 s by default). Don't raise the pool size to match: the database has its own limits. Instead, decide how much concurrency the database should see, and accept that requests wait for it. - Downstream services. A partner API with a rate limit sees 10 times the traffic as soon as the thread pool stops throttling it. Put a semaphore or a bulkhead (for example Resilience4j's) in front of it (article 12).
@Asyncwork.spring.task.execution.simple.concurrency-limitcaps the auto-configuredSimpleAsyncTaskExecutor. Withspring.task.execution.simple.reject-tasks-when-limit-reached=true, it rejects extra tasks instead of making them wait.
3. Pinning on Java 21 to 23
On Java 21 to 23, a virtual thread that blocks inside synchronized pins its carrier (article 13). Older JDBC drivers, connection pools and logging appenders used synchronized around I/O. On those releases, update drivers and libraries (many replaced synchronized with ReentrantLock), and watch the jdk.VirtualThreadPinned JFR event. On Java 24 and later, synchronized no longer pins, which is why Spring recommends it.
4. Per-thread caches
Libraries that cache expensive objects in ThreadLocal, assuming a few hundred long-lived threads, create one per virtual thread instead, and lose them when the thread ends (article 15). Look for growing allocation rates after the switch. Most mainstream libraries have since adapted.
5. CPU-bound endpoints
An endpoint that renders large reports or computes for seconds holds a carrier thread the whole time, with the problems from articles 10 and 23: other virtual threads wait for a free carrier. Move heavy computation to a bounded platform-thread pool.
Monitoring
- Thread dumps. The Actuator
threaddumpendpoint andjstackuse the classic thread APIs, which don't list virtual threads. Usejcmd <pid> Thread.dump_to_file -format=json dump.json, which shows every virtual thread and, with structured concurrency, its scope (article 36). - JFR.
jdk.VirtualThreadPinnedandjdk.VirtualThreadSubmitFailedare on by default.jdk.VirtualThreadStartandEndcan be enabled for short investigations (article 16). - Metrics. Micrometer's
micrometer-java21module has a virtual-thread binder that counts pinning events and failed submits, which Actuator can export. - The real bottlenecks. After the switch, the interesting metrics are no longer the busy Tomcat threads, but the connection pool's pending count, downstream latency and error rates: that's where the waiting has moved.
What's current
- Spring Boot 3.2 (November 2023) introduced
spring.threads.virtual.enabled. Boot 3.5 addedspring.task.execution.simple.reject-tasks-when-limit-reached. - Spring Boot 4.0 (November 2025, on Spring Framework 7) keeps Java 17 as the minimum and supports up to Java 25. Virtual threads still need Java 21+, and the property is still
falseby default. Boot 4.0 also removed Undertow support, because Undertow had no Servlet 6.1-compatible release, which leaves Tomcat and Jetty. - Spring Boot 4.0 extended the property to auto-configured JDK
HttpClient-based clients.
Common questions
Do I still need WebFlux for scalability? Not for typical request/response services: Spring MVC on virtual threads handles high concurrency of I/O-bound requests with blocking code. WebFlux remains the choice for streaming and fully reactive stacks (article 47).
Does @Transactional work on virtual threads?
Yes. Spring binds the transaction and its connection to the current thread with thread-locals, and the whole request runs on one virtual thread. Like before, a transaction doesn't follow work you hand to another thread, such as an @Async call.
Should I enable virtual threads everywhere at once? Start with one service. Measure throughput, latency and connection-pool wait times under realistic load before and after, check that limits are set explicitly, and then roll out further.
Is spring.threads.virtual.enabled on by default in Spring Boot 4?
No. It defaults to false in both 3.x and 4.x, because Spring Boot still supports Java 17, which has no virtual threads.
Summary
spring.threads.virtual.enabled=true(Spring Boot 3.2+, Java 21+, ideally 24+) moves Tomcat or Jetty requests,@Async, async MVC, WebFlux blocking calls and@Scheduledto virtual threads, and since Boot 4.0, JDKHttpClient-based clients.- In the run above, 200 slow requests that took over 1.8 seconds with 20 pooled threads finished in under a second, without code changes.
- Executor beans you define yourself are not changed. Build custom executors with
SimpleAsyncTaskExecutorBuilder. - Set
spring.main.keep-alive=true, because virtual threads are daemon threads. - Thread pools used to limit concurrency implicitly. Set limits explicitly: connection pools, semaphores and
spring.task.execution.simple.concurrency-limit. - Use
jcmd Thread.dump_to_file, JFR and Micrometer's virtual-thread metrics for monitoring.
Practice questions
After enabling virtual threads, a service handles more requests per second, but some requests now fail after 30 seconds with "Connection is not available, request timed out". What changed, and what should you do?
Answer
Before, 200 Tomcat threads limited how many requests competed for the 10 HikariCP connections. Now thousands of requests do, and some wait longer than HikariCP's connection-timeout of 30 s. Don't simply raise the pool to thousands, since the database can't handle that. Measure the database's real capacity, size the pool for it, limit concurrency in front of the database (a semaphore), and fail fast or shed load beyond that, with a shorter timeout and a clear error.
A batch application has no web server. Its only work is a @Scheduled job. After enabling virtual threads, it starts and exits immediately. Why, and what fixes it?
Answer
With virtual threads, the scheduler runs jobs on virtual threads, which are daemon threads. With no web server, no non-daemon thread remains after startup, so the JVM exits. Setting spring.main.keep-alive=true keeps a non-daemon thread running.
A team sets spring.threads.virtual.enabled=true, but logs show @Async methods still running on threads named async-exec-3. What's the likely cause?
Answer
The application defines its own Executor bean, for example a ThreadPoolTaskExecutor with the prefix async-exec-. Boot only auto-configures the virtual-thread executor when no Executor bean exists. Remove the custom bean, or rebuild it with the injected SimpleAsyncTaskExecutorBuilder, or keep it deliberately if those tasks are CPU-bound.
Previous: Reactive Programming vs Virtual Threads in Java: How to Choose
Next: Virtual Threads in Quarkus, Jakarta EE, Helidon and Micronaut

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.