Video in progress

What is a virtual thread in Java 21, and how does it differ from a regular thread?

A virtual thread is a lightweight thread managed by the JVM. It sits on an OS thread only while it is running, and frees it while waiting for I/O. So you can open millions of virtual threads.

📖 Answer

A regular (platform) thread is a wrapper around an OS thread. Each reserves about 1 MB of stack and is expensive to create, so a pool rarely holds more than a few hundred.

A virtual thread lives on the heap. The JVM rotates them over a few "carrier" threads (usually equal to the number of CPU cores). If the code waits for a DB response, the virtual thread comes off the carrier, and the carrier picks up another task.

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10_000; i++) {
        int id = i;
        executor.submit(() -> httpClient.send(requestFor(id), ofString()));
    }
} // waits for everything to finish

When it helps: jobs that wait a lot and are heavy on I/O, such as HTTP calls and DB queries. In Spring Boot 3.2+ you turn it on with spring.threads.virtual.enabled=true.

When it doesn't: CPU-heavy computation. The number of cores doesn't change, and virtual threads don't make computation faster.

Don't put them in a pool. A new one is created for every task, and that is cheap.