Sub topic 14
Virtual Threads in Java 21
What a virtual thread is
Every thread you have used so far is a platform thread. A platform thread is a Java thread backed by one thread of the operating system. Operating system threads use a lot of memory, and they are slow to create. Most programs can only run a few thousand of them at a time.
A virtual thread is a lightweight thread that the Java runtime manages, not the operating system. Java 21 added them. You can start millions of virtual threads, because each one needs very little memory.
Why they matter
Many tasks spend most of their time waiting, for example on a web request, a database, or a file. A waiting task that holds a platform thread wastes that thread. When a virtual thread waits, Java takes it off its carrier thread. A carrier thread is a platform thread that runs virtual threads. That carrier is then free to run a different virtual thread. When the wait ends, Java puts the virtual thread back on a carrier and it continues.
Starting one virtual thread
The Thread.ofVirtual() method returns a builder. A builder is an object that sets options and then creates something. Here it creates a virtual thread, and join works the same way it does on any other thread.
public class OneVirtual {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.ofVirtual()
.name("virtual-1")
.start(() -> System.out.println("Hello from " + Thread.currentThread()));
t.join();
}
}Using a per-task executor
The usual way to use virtual threads is with Executors.newVirtualThreadPerTaskExecutor(). This executor does not keep a pool. It starts a new virtual thread for every task you submit. Virtual threads are cheap, so you do not need to reuse them.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class VirtualThreadsDemo {
public static void main(String[] args) {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
int id = i;
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100));
return id;
});
}
}
System.out.println("All tasks finished");
}
}Each of the ten thousand tasks sleeps for 100 milliseconds, and the whole program still finishes in well under a second. A fixed pool of 10 platform threads would need about 100 seconds for the same work.
The try (...) line is try-with-resources, which calls close() automatically when the block ends. In Java 19 and later, ExecutorService.close() shuts the executor down and waits for every submitted task to finish. You do not have to write the shutdown and awaitTermination pattern yourself.
When to use them
| Kind of task | Good choice |
|---|---|
| Mostly waiting (network, files, databases) | Virtual threads |
| Mostly calculating (math, image processing) | Fixed pool sized to your CPU cores |
| Needs a limit on how many run at once | Fixed pool, or a limit you add yourself |
Virtual threads do not make calculations faster, because the work still runs on the same CPU cores. They help when you have many tasks that spend their time waiting.
Everything you learned earlier still applies. Shared data still needs synchronized or atomic variables, and Future.get still reports task errors as ExecutionException.
Exercise
Your program makes 5,000 web requests, and each one waits about 200 milliseconds for a reply. Should you use Executors.newFixedThreadPool(8) or Executors.newVirtualThreadPerTaskExecutor()? Explain why.
Show answer
Use newVirtualThreadPerTaskExecutor(). The tasks spend most of their time waiting. With 8 platform threads, only 8 requests can wait at once, so the run takes about 125 seconds. With virtual threads, all 5,000 requests can wait at the same time while a few carrier threads stay busy, so the run finishes in roughly the time of one request plus some overhead.
Exercise
In VirtualThreadsDemo, why does "All tasks finished" print only after every task is done, even though the code never calls shutdown or awaitTermination?
Show answer
The executor is created in a try-with-resources block. When the block ends, Java calls executor.close(), which shuts the executor down and waits for all submitted tasks to finish before the next line runs.