Virtual Threads in Spring Boot
Virtual threads in Spring Boot let a normal, blocking application handle far more concurrent requests without rewriting it in a reactive style. A virtual thread is a lightweight thread managed by the JVM: when it waits for a database, an HTTP call or a file, it gives up its carrier thread so another task can run. In Spring Boot, one property switches the web server, @Async methods, scheduled tasks and several messaging integrations to virtual threads.
This tutorial explains how virtual threads differ from platform threads, what exactly changes when you enable them in Spring Boot, and how to measure the effect with a small order API that calls a slow downstream service. It also covers the limits you must still respect, such as connection pools, pinning, thread-local state and daemon threads.
1. What Are Virtual Threads?
A traditional Java thread, now called a platform thread, is a thin wrapper around an operating system thread. Each one reserves memory for its stack and is expensive to create, so servers keep them in pools of a few hundred.
A virtual thread (final since Java 21) is a java.lang.Thread that is not tied to one OS thread. The JVM runs many virtual threads on a small set of platform threads called carrier threads. Virtual threads are cheap enough to create one per task, even millions of them, and you program them with ordinary blocking code.
2. Why Virtual Threads Matter for Spring Boot
Most Spring Boot services are I/O-bound: a request spends most of its time waiting for a database, a cache or another service. With platform threads, Tomcat's default pool of 200 threads means at most 200 requests can wait at the same time; request 201 queues even though the CPU is idle.
| Aspect | Platform thread per request | Virtual thread per request | Reactive (WebFlux) |
|---|---|---|---|
| Programming model | Blocking, simple | Blocking, simple | Non-blocking, operators |
| Concurrent waiting requests | Limited by the thread pool | Limited by memory and downstream resources | Very high |
| Code changes needed | None | One property, plus reviewing limits | A rewrite |
| Stack traces and debugging | Easy | Easy | Harder |
| CPU-heavy work | Fine | No benefit | No benefit |
3. How Virtual Threads Work
The key mechanism is mounting and unmounting. When a virtual thread blocks on supported I/O, such as sockets used by JDBC drivers and HTTP clients, the JVM removes it from its carrier and parks it. The carrier immediately runs another virtual thread. Blocking becomes cheap, so you can keep writing simple blocking code.
Virtual threads do not make code run faster. They let more tasks wait at the same time. The gain shows up as higher throughput when requests spend most of their time waiting.
4. Enabling Virtual Threads in Spring Boot
Run on Java 21 or later and set one property:
spring.threads.virtual.enabled=true
spring.main.keep-alive=true
Spring Boot's documentation strongly recommends Java 24 or later for the best experience, so Java 25, the current LTS release, is the natural choice. The second property is explained in section 8.4.
spring.threads.virtual.enabled in 3.2. Java 24 (JEP 491) removed the most common cause of pinning: virtual threads no longer pin their carrier while blocking inside synchronized blocks. On Java 21, prefer ReentrantLock over synchronized around blocking I/O.5. What Changes When You Enable Them
| Component | Without virtual threads | With virtual threads |
|---|---|---|
| Embedded Tomcat or Jetty request handling | Pool of platform threads (Tomcat default max 200) | A new virtual thread per request |
Auto-configured applicationTaskExecutor (@Async, async MVC) | ThreadPoolTaskExecutor | SimpleAsyncTaskExecutor using virtual threads |
Auto-configured task scheduler (@Scheduled) | ThreadPoolTaskScheduler, one thread by default | SimpleAsyncTaskScheduler using virtual threads |
| Messaging listener containers and other integrations | Platform threads | Virtual threads for supported integrations (see the Spring Boot docs for the current list) |
Thread pool properties (server.tomcat.threads.max, spring.task.execution.pool.*) | Applied | No longer have an effect |
Executors and schedulers you define yourself are not changed. If you create a ThreadPoolTaskExecutor bean, it stays a platform thread pool. Async processing in general is covered in async processing in Spring Boot.
6. A Complete Example: Many Slow Downstream Calls
An order API checks stock with an inventory service that takes about 300 ms to answer. We send 1,000 concurrent requests and compare platform and virtual threads.
6.1 The Inventory Client
package com.javabytechie.shop.order;
import org.springframework.stereotype.Component;
@Component
public class InventoryClient {
public boolean inStock(String sku) throws InterruptedException {
Thread.sleep(300); // stands in for a blocking HTTP or JDBC call
return !sku.startsWith("OUT-");
}
}
6.2 The Controller
package com.javabytechie.shop.order;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/stock")
public class StockController {
private final InventoryClient inventory;
public StockController(InventoryClient inventory) {
this.inventory = inventory;
}
@GetMapping("/{sku}")
public StockStatus check(@PathVariable String sku) throws InterruptedException {
boolean available = inventory.inStock(sku);
Thread current = Thread.currentThread();
return new StockStatus(sku, available, current.isVirtual(), current.toString());
}
public record StockStatus(String sku, boolean available, boolean virtualThread, String thread) {
}
}
6.3 A Small Load Generator
This client also uses virtual threads, so it can open 1,000 concurrent requests without its own limit getting in the way:
package com.javabytechie.shop.tools;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class LoadTest {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
long start = System.nanoTime();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 1_000).forEach(i -> executor.submit(() -> client.send(
HttpRequest.newBuilder(URI.create("http://localhost:8080/api/stock/KB-" + i)).build(),
HttpResponse.BodyHandlers.discarding())));
} // close() waits for all tasks
System.out.printf("1000 requests in %d ms%n", (System.nanoTime() - start) / 1_000_000);
}
}
6.4 Results
# spring.threads.virtual.enabled=false (Tomcat max 200 threads)
1000 requests in 1712 ms
# spring.threads.virtual.enabled=true
1000 requests in 431 ms
The numbers follow from simple arithmetic: with 200 platform threads, 1,000 requests of 300 ms need at least five rounds, about 1.5 seconds. With virtual threads, all 1,000 wait at the same time, so the total is close to one request's latency plus overhead. Your numbers will differ, but the ratio is what matters.
{"sku":"KB-100","available":true,"virtualThread":true,"thread":"VirtualThread[#68,tomcat-handler-12]/runnable@ForkJoinPool-1-worker-3"}
The thread string shows a virtual thread named by Tomcat, currently running on a ForkJoinPool worker, which is its carrier. Exact names and numbers vary.
7. Limits You Still Need
Virtual threads remove the thread pool as a natural limit. The limits of everything behind the threads remain, so a traffic spike now reaches them directly.
- Database connection pools: HikariCP has 10 connections by default. With 1,000 virtual threads wanting a connection, 990 wait in the pool. That is fine, but size the pool for the database and set a sensible
spring.datasource.hikari.connection-timeout. - Downstream services: another service may not cope with 1,000 parallel calls. Limit concurrency per client with
@ConcurrencyLimitor a semaphore; see retry and resilience in Spring Boot. - Async tasks: the virtual-thread
SimpleAsyncTaskExecutorhas no limit by default. Setspring.task.execution.simple.concurrency-limitif tasks should not run unbounded. - Memory: each waiting request still holds its objects and stack on the heap. Very high concurrency needs heap headroom.
spring.datasource.hikari.maximum-pool-size=30
spring.datasource.hikari.connection-timeout=2s
spring.task.execution.simple.concurrency-limit=100
8. Pinning and Other Pitfalls
8.1 Pinning
A virtual thread is pinned when it cannot unmount while blocked, so it keeps its carrier busy. Since there are only a few carriers, a few pinned threads can stall the whole application. On Java 24 and later, synchronized no longer causes pinning; the remaining cases are mostly native code and some class-initialization situations. Detect pinning with JDK Flight Recorder's jdk.VirtualThreadPinned event.
8.2 ThreadLocal Overuse
Thread-local values work on virtual threads, but each of thousands of threads gets its own copy, and caching expensive objects in thread-locals, a common trick with pools, stops paying off. For passing request context down a call chain, Java 25's scoped values (ScopedValue) are a lighter, immutable alternative.
8.3 Pooling Virtual Threads
Never put virtual threads in a pool. They are meant to be created per task; limit concurrency with semaphores or concurrency limits instead.
8.4 Daemon Threads and keep-alive
Virtual threads are always daemon threads, and the JVM exits when only daemon threads remain. An application without a web server, for example one that only runs @Scheduled jobs, could shut down right after startup. spring.main.keep-alive=true keeps the JVM running in that case.
8.5 CPU-Bound Work
Image processing, encryption of large files or heavy calculations keep a carrier busy the whole time. Virtual threads bring no benefit there; use a bounded platform thread pool for such work.
9. Checking and Testing Virtual Threads
A web slice test runs on MockMvc, not on a real server thread, so check thread types with a full server test:
package com.javabytechie.shop.order;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.web.client.RestClient;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "spring.threads.virtual.enabled=true")
class StockControllerVirtualThreadTest {
@LocalServerPort
int port;
@Test
void requestsRunOnVirtualThreads() {
StockController.StockStatus status = RestClient.create("http://localhost:" + port)
.get().uri("/api/stock/KB-100")
.retrieve()
.body(StockController.StockStatus.class);
assertThat(status).isNotNull();
assertThat(status.virtualThread()).isTrue();
assertThat(status.available()).isTrue();
}
}
Running the same test with spring.threads.virtual.enabled=false returns virtualThread: false, which makes a useful guard if someone switches the property off by mistake. In production, the Actuator threaddump endpoint and JDK Flight Recorder show virtual threads and pinning events.
10. When to Use Virtual Threads and When Not To
| Good fit | Poor fit |
|---|---|
| REST APIs that call databases and other services | CPU-bound processing |
| Fan-out to several downstream services per request | Code that relies on native libraries that block (pinning) |
| Applications hitting the Tomcat thread limit under load | Services whose bottleneck is the database, not threads |
| Teams that want throughput without moving to WebFlux | Applications that cannot run on Java 21 or later |
11. Best Practices
- Run on Java 25 to avoid
synchronizedpinning and get the latest scheduler improvements. - Enable with
spring.threads.virtual.enabled=trueinstead of creating executors by hand. - Set
spring.main.keep-alive=truefor applications without a web server. - Keep connection pools and downstream limits explicit; virtual threads remove the old implicit limit.
- Never pool virtual threads; limit concurrency with
@ConcurrencyLimitor semaphores. - Measure before and after with a realistic load test, and watch database and downstream latency.
- Keep CPU-heavy work on bounded platform thread pools.
12. Summary
Virtual threads in Spring Boot give blocking code the scalability that used to require reactive programming. Set spring.threads.virtual.enabled=true on Java 21 or later, ideally Java 25, and Tomcat or Jetty, the auto-configured @Async executor, the scheduler and supported messaging integrations all use virtual threads, while thread pool properties stop applying. The application can then keep thousands of requests waiting on I/O at once, so the real limits move to connection pools, downstream services and memory, which you must size and protect. Watch for pinning, avoid pooling virtual threads, enable spring.main.keep-alive for non-web applications, and measure the gain with a realistic load test.
13. References
Virtual Threads in Spring Boot Interview Questions and Answers
Common interview questions on Virtual Threads in Spring Boot, from basic to scenario-based, with short answers you can explain in your own words.
Q. What is a virtual thread, and how is it different from a platform thread?
Answer: A platform thread wraps one operating system thread for its whole life and is expensive, so applications pool a few hundred. A virtual thread is a lightweight Thread scheduled by the JVM onto a few carrier threads; when it blocks on I/O it is unmounted and its carrier runs other work. Virtual threads are cheap enough to create one per task, which lets blocking code scale to many concurrent waits.
Q. What happens in Spring Boot when you set spring.threads.virtual.enabled=true?
Answer: Tomcat or Jetty handle each request on a new virtual thread, the auto-configured applicationTaskExecutor becomes a virtual-thread SimpleAsyncTaskExecutor, the auto-configured scheduler becomes a SimpleAsyncTaskScheduler, and supported integrations such as some message listener containers use virtual threads. Thread pool size properties stop having an effect. Executors you define yourself are not changed.
Q. Should you put virtual threads in a thread pool to limit how many run at once?
Answer: No. Virtual threads are meant to be created per task and thrown away; pooling them adds overhead and brings back the old limits. To limit concurrency, keep one virtual thread per task and guard the scarce resource instead, with a Semaphore, @ConcurrencyLimit, a connection pool size or spring.task.execution.simple.concurrency-limit for async tasks.
Q. What is pinning, and is synchronized still a problem?
Answer: Pinning happens when a blocked virtual thread cannot unmount and keeps its carrier thread busy, which can starve the small carrier pool. On Java 21 to 23, blocking inside synchronized pinned the thread, so ReentrantLock was recommended. Java 24 (JEP 491) removed that cause; remaining cases involve native code and are visible as jdk.VirtualThreadPinned events in JDK Flight Recorder.
Q. Why is spring.main.keep-alive recommended with virtual threads?
Answer: Virtual threads are always daemon threads, and the JVM exits when no non-daemon threads remain. A web application is kept alive by its server, but an application that only runs scheduled tasks or message listeners on virtual threads could exit right after startup. spring.main.keep-alive=true keeps a non-daemon thread alive so the JVM keeps running.
Q. After enabling virtual threads, the service handles more requests but the database starts timing out. What happened, and how do you fix it?
Answer: The Tomcat thread pool used to cap concurrency at about 200; with virtual threads, many more requests reach the connection pool and the database at once. Size the HikariCP pool for what the database can handle, set a short connection timeout so callers fail fast, and limit concurrency for expensive operations with @ConcurrencyLimit or a semaphore. Also look at slow queries, which now dominate latency.