Virtual Threads in 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
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
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());
}
}
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.
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");
}
}
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
5. Virtual vs Platform Threads
| Aspect | Platform thread | Virtual thread |
|---|---|---|
| Backed by | one OS thread for its whole life | a carrier thread only while running |
| Creation cost | high (OS call, about 1 MB stack) | low (small heap object) |
| Typical count | hundreds to a few thousand | millions possible |
| Pooling | recommended | not needed; create per task |
| Best for | CPU-heavy work | I/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
synchronizedblock pins the carrier thread; preferReentrantLockthere. Java 24 removed this limitation (JEP 491). - Be careful with large
ThreadLocalvalues: 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
- Structured Concurrency (Preview)
- Scoped Values (Preview)
- CompletableFuture (Java 8)
- Multithreading in Java
8. References
Frequently Asked Questions (FAQ)
Q1. What are virtual threads in Java?
Lightweight threads implemented by the JVM. They run on a small number of carrier platform threads and are unmounted while they wait for I/O. They became standard in Java 21.
Q2. Should virtual threads be pooled?
No. They are cheap to create, so the recommended style is one new virtual thread per task.
Q3. Do virtual threads make code faster?
They increase throughput for tasks that spend most of their time waiting. They do not make CPU-bound computations faster.
Q4. What is thread pinning?
In Java 21, a virtual thread that blocks inside a synchronized block or a native call cannot unmount, so it occupies its carrier thread. Java 24 fixed the synchronized case.