Medium java java-21

What are virtual threads?

The 30 second answer

Virtual threads, final in Java 21, are lightweight threads managed by the JDK instead of the operating system. They are still normal Thread objects, so ordinary blocking code works. When a virtual thread waits on I/O, the JDK unmounts it from the real OS thread underneath, and that OS thread runs another virtual thread. So I can have one thread per request, even with a huge number of requests.

Virtual threads were previewed in Java 19 and 20 and became final in Java 21 (JEP 444).

try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (var req : requests) executor.submit(() -> handle(req));
}   // close() waits for submitted tasks

Thread.ofVirtual().name("worker").start(() -> callApi());
Thread.startVirtualThread(() -> callApi());

A virtual thread runs on a carrier platform thread from a dedicated ForkJoinPool scheduler. When it blocks on most JDK I/O, sleep, or java.util.concurrent locks and queues, its stack is saved to the heap and the carrier is freed. When the operation completes, it is scheduled again, possibly on another carrier.

Virtual threads are always daemon threads, and they are meant to be created per task, never pooled.

Sources: JEP 444: Virtual Threads, Oracle guide: Virtual Threads

Sources (0)
See inline citations in the answer above.