00:00

Virtual Threads in Java 21

Last updated: · Standard (Java 21)

Virtual threads are lightweight threads managed by the JVM rather than the operating system. They became a standard feature in Java 21 (JEP 444), after previews in Java 19 and 20, and make it practical to run one thread per task even with tens of thousands of concurrent tasks.

This tutorial explains how virtual threads work, how to create them, and where they help and where they do not.

1. Why Were Virtual Threads Added?

A classic Java thread is a thin wrapper around an operating-system thread. OS threads are expensive, so servers limit them with thread pools. When a pooled thread waits for a database or HTTP call, it does nothing but is still occupied, which caps throughput. The alternative, asynchronous code with callbacks or CompletableFuture, scales better but is harder to write, debug and read.

Virtual threads keep the simple blocking style: when a virtual thread blocks on I/O, the JVM unmounts it and uses the underlying OS thread for other work.

2. Ways to Create Virtual Threads

Syntax.java
Thread.startVirtualThread(task);                      // start one
Thread.ofVirtual().name("worker").start(task);        // builder
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    executor.submit(task);                            // one new virtual thread per task
}

3. Practical Examples

Example 1: Creating virtual threads

CreatingVirtualThreads.java
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CreatingVirtualThreads {
    public static void main(String[] args) throws Exception {
        // 1. Start one virtual thread directly
        Thread t1 = Thread.startVirtualThread(() -> System.out.println("1: virtual = " + Thread.currentThread().isVirtual()));
        t1.join();

        // 2. Builder with a name
        Thread t2 = Thread.ofVirtual().name("report-worker").start(
                () -> System.out.println("2: running in " + Thread.currentThread().getName()));
        t2.join();

        // 3. Executor: one new virtual thread per submitted task
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            Future<String> result = executor.submit(() -> "3: result from a virtual thread");
            System.out.println(result.get());
        }

        // Platform threads still exist and are created the usual way
        Thread platform = Thread.ofPlatform().unstarted(() -> { });
        System.out.println("platform builder creates virtual? " + platform.isVirtual());
    }
}
Output
1: virtual = true
2: running in report-worker
3: result from a virtual thread
platform builder creates virtual? false

Example 2: Blocking tasks at scale

Each task sleeps for one second to imitate a slow I/O call. Ten thousand tasks on virtual threads finish in about one second; one thousand tasks on a pool of 100 platform threads take about ten seconds, because only 100 can wait at a time.

VirtualVsPlatform.java
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class VirtualVsPlatform {
    // Each task waits 1 second, like a slow database or HTTP call
    static void runTasks(ExecutorService executor, int tasks) {
        try (executor) {                               // close() waits for all tasks
            IntStream.range(0, tasks).forEach(i -> executor.submit(() -> {
                Thread.sleep(Duration.ofSeconds(1));
                return i;
            }));
        }
    }

    public static void main(String[] args) {
        Instant start = Instant.now();
        runTasks(Executors.newVirtualThreadPerTaskExecutor(), 10_000);
        long virtualMs = Duration.between(start, Instant.now()).toMillis();
        System.out.println("10,000 blocking tasks on virtual threads: under 3 s? " + (virtualMs < 3000));

        start = Instant.now();
        runTasks(Executors.newFixedThreadPool(100), 1_000);
        long poolSeconds = Duration.between(start, Instant.now()).toSeconds();
        System.out.println("1,000 tasks on 100 platform threads took about " + poolSeconds + " s");
    }
}
Output
10,000 blocking tasks on virtual threads: under 3 s? true
1,000 tasks on 100 platform threads took about 10 s

4. How Virtual Threads Run

Mounting and unmounting virtual threads Many virtual threads are scheduled onto a small pool of carrier platform threads. When a virtual thread blocks on I/O it is unmounted, its stack is stored on the heap, and the carrier runs another virtual thread. 10,000 virtual threads cheap Java objects scheduler ForkJoinPool few carrier threads ~ one per CPU core blocking call unmount, run another
Figure 1: Virtual threads multiply concurrency for waiting tasks, not raw CPU speed.

5. Virtual vs Platform Threads

AspectPlatform threadVirtual thread
Backed byone OS thread for its whole lifea carrier thread only while running
Creation costhigh (OS call, about 1 MB stack)low (small heap object)
Typical counthundreds to a few thousandmillions possible
Poolingrecommendednot needed; create per task
Best forCPU-heavy workI/O-heavy, blocking work

6. Important Points and Best Practices

  • Do not pool virtual threads; create a new one per task.
  • Use them for I/O-bound work. CPU-bound code gains nothing from more threads than cores.
  • Limit access to scarce resources such as database connections with a Semaphore, not with a small thread pool.
  • In Java 21, blocking inside a synchronized block pins the carrier thread; prefer ReentrantLock there. Java 24 removed this limitation (JEP 491).
  • Be careful with large ThreadLocal values: with millions of threads they add up; consider scoped values.

7. Summary

  • Virtual threads are lightweight threads, final in Java 21 (JEP 444).
  • They are created per task, for example with Executors.newVirtualThreadPerTaskExecutor().
  • Blocking I/O unmounts the virtual thread and frees its carrier.
  • They improve throughput for I/O-heavy code, not CPU-heavy code.

Related Tutorials

8. References