Java core learning path Level 2 This level · 5 of 29
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.

Could you say this in an interview?

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.

Alternate interview scenarios

"Do virtual threads help with CPU-bound work, and what is pinning?"

They do not help CPU-bound work. JEP 444 says that having many more threads than processor cores cannot improve throughput when the workload is CPU-bound, and the Thread Javadoc says virtual threads "are not intended for long running CPU intensive operations." For that work I keep a small pool of platform threads, about the core count. Pinning is a separate I/O-scalability issue. In Java 21, 22 and 23, a virtual thread that blocks inside a synchronized method or block, or in a native call, stays pinned to its carrier, so that platform thread cannot run other virtual threads. JEP 444 suggested ReentrantLock around frequent, long blocking operations, and -Djdk.tracePinnedThreads to find them. Java 24 (JEP 491) removed the synchronized pinning case; native calls can still pin.

Sources (4)
  1. JEP 444: Virtual Threadsopenjdk.org
  2. Oracle guide: Virtual Threadsdocs.oracle.com
  3. Thread Javadoc (Java 21): virtual threadsdocs.oracle.com
  4. JEP 491: Synchronize Virtual Threads without Pinningopenjdk.org
Previous
Next