00:00

Virtual Threads in Spring Boot

Last updated:

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.

Analogy: Platform threads are like a restaurant where each waiter serves one table from order to payment, standing idle while the kitchen cooks. Virtual threads are like waiters who take an order, hand it to the kitchen and serve other tables meanwhile, returning when the dish is ready. The same staff serves many more tables.

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.

AspectPlatform thread per requestVirtual thread per requestReactive (WebFlux)
Programming modelBlocking, simpleBlocking, simpleNon-blocking, operators
Concurrent waiting requestsLimited by the thread poolLimited by memory and downstream resourcesVery high
Code changes neededNoneOne property, plus reviewing limitsA rewrite
Stack traces and debuggingEasyEasyHarder
CPU-heavy workFineNo benefitNo benefit

3. How Virtual Threads Work

Virtual threads mounted on carrier threadsMany virtual threads, one per request, are scheduled by the JVM onto a small pool of carrier threads, roughly one per CPU core. When a virtual thread blocks on I/O, such as a JDBC query or an HTTP call, the JVM unmounts it and saves its stack to the heap, freeing the carrier to run another virtual thread. When the I/O completes, the virtual thread is mounted again on any free carrier and continues. Virtual threads one per request (thousands) request 1, request 2, ... cheap, stack on the heap JVM scheduler carrier threads about one per CPU core (ForkJoinPool) Blocked on I/O JDBC query, HTTP call: unmounted, carrier freed I/O completes mounted again on any free carrier
A blocked virtual thread releases its carrier; the carrier immediately runs another request.

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:

application.properties
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.

Version note: Spring Boot added 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

ComponentWithout virtual threadsWith virtual threads
Embedded Tomcat or Jetty request handlingPool of platform threads (Tomcat default max 200)A new virtual thread per request
Auto-configured applicationTaskExecutor (@Async, async MVC)ThreadPoolTaskExecutorSimpleAsyncTaskExecutor using virtual threads
Auto-configured task scheduler (@Scheduled)ThreadPoolTaskScheduler, one thread by defaultSimpleAsyncTaskScheduler using virtual threads
Messaging listener containers and other integrationsPlatform threadsVirtual threads for supported integrations (see the Spring Boot docs for the current list)
Thread pool properties (server.tomcat.threads.max, spring.task.execution.pool.*)AppliedNo 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

InventoryClient.java
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

StockController.java
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:

LoadTest.java
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

Console (typical laptop run)
# 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.

GET /api/stock/KB-100 (with virtual threads)
{"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 @ConcurrencyLimit or a semaphore; see retry and resilience in Spring Boot.
  • Async tasks: the virtual-thread SimpleAsyncTaskExecutor has no limit by default. Set spring.task.execution.simple.concurrency-limit if tasks should not run unbounded.
  • Memory: each waiting request still holds its objects and stack on the heap. Very high concurrency needs heap headroom.
application.properties
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:

StockControllerVirtualThreadTest.java
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 fitPoor fit
REST APIs that call databases and other servicesCPU-bound processing
Fan-out to several downstream services per requestCode that relies on native libraries that block (pinning)
Applications hitting the Tomcat thread limit under loadServices whose bottleneck is the database, not threads
Teams that want throughput without moving to WebFluxApplications that cannot run on Java 21 or later

11. Best Practices

  • Run on Java 25 to avoid synchronized pinning and get the latest scheduler improvements.
  • Enable with spring.threads.virtual.enabled=true instead of creating executors by hand.
  • Set spring.main.keep-alive=true for 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 @ConcurrencyLimit or 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