Articles Java

Java virtual threads: when to use them and when not

Use virtual threads when your application runs many concurrent tasks that spend most of their time waiting: HTTP calls, JDBC queries, message brokers, file and socket I/O. A thread-per-request web service is the textbook case. Do not expect anything from them for CPU-bound work, and on Java 21 check for synchronized blocks around I/O before you switch. Virtual threads are final since Java 21 (JEP 444), and the biggest practical limitation was removed in Java 24.

What is a virtual thread in Java?

A platform thread is a thin wrapper around an operating system thread. It is expensive to create, so you keep a few hundred of them in a pool and hand them out to tasks. A virtual thread is an ordinary java.lang.Thread that the JDK schedules itself. Its stack lives on the heap and grows as needed, so a JVM can hold hundreds of thousands of them.

Virtual threads run on a small set of platform threads called carriers, by default one per CPU core. When a virtual thread blocks, for example in Thread.sleep, a socket read or BlockingQueue.take(), the JDK unmounts it from its carrier, and the carrier picks up another virtual thread. Your code stays plain blocking code. Only the cost of blocking changes.

When do virtual threads help?

They help when the number of threads is your limit, not the CPU. A pool of 200 platform threads can wait on 200 things at once. Request 201 queues, even when the CPU is idle and the database could take more.

This program submits 10 000 tasks that each block for 100 ms, first to a fixed pool and then to an executor that starts one virtual thread per task:

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SleepDemo {
    static final int TASKS = 10_000;

    public static void main(String[] args) {
        run("fixed pool, 200 platform threads", Executors.newFixedThreadPool(200));
        run("virtual thread per task", Executors.newVirtualThreadPerTaskExecutor());
    }

    static void run(String name, ExecutorService executor) {
        long start = System.nanoTime();
        try (executor) {
            for (int i = 0; i < TASKS; i++) {
                executor.submit(() -> {
                    Thread.sleep(Duration.ofMillis(100)); // stands in for a blocking call
                    return null;
                });
            }
        } // close() waits for every task to finish
        long ms = (System.nanoTime() - start) / 1_000_000;
        System.out.println(name + ": " + ms + " ms");
    }
}

On a 6-core machine with JDK 25.0.3 it printed:

fixed pool, 200 platform threads: 5179 ms
virtual thread per task: 149 ms

Treat this as an illustration, not a benchmark: one run, no warmup, and sleep is the friendliest blocking call there is. The pool result is plain arithmetic, 10 000 tasks divided by 200 threads times 100 ms. The point is the shape. With virtual threads, all 10 000 tasks wait at the same time.

When do virtual threads not help?

CPU-bound work. A virtual thread does not run code faster than a platform thread, and you cannot compute on more cores than you have. The same experiment with 64 tasks that each spin in a calculation loop gave 4368 ms on a pool with one thread per core and 4163 ms on virtual threads. That difference is noise.

The scheduler also does not time-slice virtual threads. A long calculation keeps its carrier until it finishes or blocks. For image processing, encryption, parsing large files in memory or parallel streams, keep a platform thread pool sized to the core count.

They also do not help when you have few concurrent tasks, or when the bottleneck is elsewhere. Ten thousand virtual threads in front of a connection pool of 10 still run 10 queries at a time.

Do synchronized blocks still pin virtual threads?

On Java 21, yes. On Java 24 and later, including 25, no.

In Java 21 to 23 a virtual thread that blocks inside a synchronized block or method cannot unmount. It stays pinned to its carrier and holds the OS thread for the whole wait. Enough of those at once and every carrier is taken, so all other virtual threads stop making progress.

int tasks = 4 * Runtime.getRuntime().availableProcessors();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < tasks; i++) {
        Object lock = new Object(); // one lock per task, so no contention
        executor.submit(() -> {
            synchronized (lock) {
                Thread.sleep(1000); // blocks while holding a monitor
            }
            return null;
        });
    }
}

On 6 cores that is 24 tasks sleeping one second each. Measured on the same machine:

JDKTime for 24 tasks
21.0.34066 ms
25.0.31016 ms

Java 21 ran them six at a time, because each sleeping task pinned one of six carriers. JEP 491, delivered in Java 24, changed the JVM so that a virtual thread inside synchronized unmounts like anywhere else. The same holds for waiting to enter a monitor and for Object.wait().

What this means in practice:

  • On Java 21: find synchronized code that guards I/O, in your code and in older library versions, and replace it with ReentrantLock, or upgrade the JDK. Short synchronized blocks around in-memory work are fine. Run with -Djdk.tracePinnedThreads=short to get a stack trace each time a thread blocks while pinned.
  • On Java 24 and 25: there is no reason to rewrite synchronized for the sake of virtual threads. The jdk.tracePinnedThreads property was removed and setting it does nothing. Use the JFR event jdk.VirtualThreadPinned for the cases that remain: blocking inside native code that called back into Java, and blocking during class loading or in a class initializer.

Should you pool virtual threads?

No. A pool exists to reuse something expensive, and a virtual thread is not expensive. Create one per task with Executors.newVirtualThreadPerTaskExecutor() or Thread.ofVirtual().start(...) and let it end.

A fixed pool had a second job that is easy to miss: it capped concurrency. Take the pool away and nothing stops 10 000 tasks from calling a service that copes with 20. Put that limit back with a Semaphore:

static final Semaphore PERMITS = new Semaphore(20);

static String callSlowService(int id) throws InterruptedException {
    PERMITS.acquire(); // a waiting virtual thread parks, it does not hold an OS thread
    try {
        return doCall(id);
    } finally {
        PERMITS.release();
    }
}

Run with 1000 virtual threads, at most 20 were inside doCall at any moment. The limit now sits next to the resource it protects, not in a thread pool configured somewhere else.

ThreadLocal with virtual threads, and scoped values

ThreadLocal works on virtual threads, so existing code keeps running. The cost is in one habit: caching an expensive object per thread, such as a buffer or a parser. That only pays off when threads are reused. With one thread per task, every task builds its own copy, uses it once and throws it away. Move such caches to a shared, bounded pool.

For passing context down a call chain (request ID, current user), Java 25 has scoped values as a final feature (JEP 506). A value is bound for the duration of a call and is immutable inside it:

static final ScopedValue<String> REQUEST_ID = ScopedValue.newInstance();

ScopedValue.where(REQUEST_ID, "req-42").run(ScopedDemo::handle);
// inside handle(): REQUEST_ID.get() returns "req-42"

In Java 21 to 24 ScopedValue is a preview API and needs --enable-preview, so on 21 stay with ThreadLocal in production code.

How to enable virtual threads in Spring Boot

One property, available since Spring Boot 3.2 and unchanged in Boot 4, on Java 21 or later:

spring.threads.virtual.enabled=true

Tomcat and Jetty then handle each request on a virtual thread, and @Async methods and @Scheduled tasks run on virtual threads too. Two consequences are documented in the Spring Boot reference:

  • Properties that size thread pools, such as server.tomcat.threads.max, no longer have an effect. Your concurrency limit is now the database connection pool and whatever semaphores you add.
  • Virtual threads are daemon threads. An application kept alive only by scheduled tasks will exit, unless you set spring.main.keep-alive=true.

The Spring Boot documentation recommends Java 24 or later for virtual threads, for the pinning reason above.

Summary: the decision rule

Count what your threads do while a request is in flight.

  • Mostly waiting on I/O, many requests at once: turn virtual threads on. On Java 25 it is a safe default for a blocking web service. On Java 21 check for pinning first.
  • Mostly computing: stay with a platform pool sized to the cores. Nothing to gain.
  • Either way: never pool virtual threads, limit access to scarce resources with a semaphore, and stop caching expensive objects in ThreadLocal.

Virtual threads raise how many things your service can wait for at once. They do not make any single one of them faster.

Sources