Sub topic 14
Virtual Threads in Java 21
Every thread you have used so far in this tutorial is a platform thread. A platform thread is a Java thread that wraps one thread of the operating system (OS). The OS thread is expensive. It reserves a large block of memory for its stack, and the OS takes time to create it and switch between threads. A typical machine can only run a few thousand platform threads before it slows down or runs out of memory.
Java 21 added a second kind of thread called the virtual thread. A virtual thread is a lightweight thread that the Java runtime manages itself, without a dedicated OS thread. You can create millions of them. This chapter explains how they work, shows how to use them through an ExecutorService, and covers the cases where they help and where they don't.
Why Platform Threads Run Out
Picture a web server that handles each request on its own thread. Most of a request's time goes to blocking, which means the thread waits for something slow, such as a database reply, a file read, or a network call. While a platform thread waits, it does no work, but its OS thread and memory stay reserved.
Suppose you have 10,000 requests and each one waits 100 milliseconds. A pool of 100 platform threads can serve only 100 requests at a time, so the other 9,900 sit in the queue. Making the pool 10,000 threads big would use far too much memory.
The usual workarounds were complicated. Programmers wrote callback code or used CompletableFuture chains so that no thread ever sat waiting. Virtual threads take a different approach. A waiting thread becomes so cheap that you can stop worrying about it.
How Virtual Threads Work Inside
The Java runtime keeps a small pool of platform threads called carrier threads. A carrier thread is a platform thread that runs virtual threads. By default there is about one carrier per CPU core.
When a virtual thread has work to do, the runtime mounts it on a carrier. Mounting means that virtual thread's code runs on that carrier. When the virtual thread blocks, for example inside Thread.sleep or while reading from a socket, the runtime unmounts it. It saves the virtual thread's state in ordinary heap memory and frees the carrier to run a different virtual thread. When the wait ends, the virtual thread is mounted again, possibly on a different carrier, and carries on from where it stopped.
Your code doesn't change. You still write plain blocking code like Thread.sleep(...) or socket.read(). The runtime does the mounting and unmounting for you.
Your First Virtual Thread
The Thread class has a builder for virtual threads. Thread.ofVirtual() returns the builder, name(...) sets an optional name, and start(...) creates and starts the thread.
public class FirstVirtualThread {
public static void main(String[] args) throws InterruptedException {
Thread vt = Thread.ofVirtual().name("virtual-1").start(() -> {
Thread me = Thread.currentThread();
System.out.println("Name: " + me.getName());
System.out.println("Virtual? " + me.isVirtual());
System.out.println("Details: " + me);
});
vt.join();
}
}The output will look something like this:
Name: virtual-1
Virtual? true
Details: VirtualThread[#21,virtual-1]/runnable@ForkJoinPool-1-worker-1The last line shows the virtual thread and, after the @, the carrier thread it is mounted on. join works the same as it does for a platform thread. There is also a shortcut, Thread.startVirtualThread(task), for when you don't need a name.
Virtual threads are always daemon threads. A daemon thread does not keep the program alive. If main ends without calling join, the program can exit before the virtual thread prints anything.
Using Virtual Threads with an ExecutorService
Most of the time you won't create virtual threads by hand. Java 21 provides Executors.newVirtualThreadPerTaskExecutor(). This executor starts a brand new virtual thread for every task you submit. It has no pool and no queue.
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");
}
}The example introduces a new piece: try-with-resources on an ExecutorService. Starting in Java 19, ExecutorService has a close method. When the try block ends, close calls shutdown and then waits until every submitted task has finished. That covers the shutdown pattern from earlier chapters in one line. The lambda returns id, so it is a Callable, and a Callable is allowed to throw the checked InterruptedException from Thread.sleep.
The executor is still an ordinary ExecutorService. Everything you learned about submit, Future, invokeAll, and ExecutionException works on it unchanged.
Worked Example: Measuring the Difference
This program runs the same 10,000 sleeping tasks twice. The first run uses a fixed pool of 100 platform threads. The second run uses virtual threads.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompareThreads {
static long run(ExecutorService executor) {
long start = System.nanoTime();
try (executor) {
for (int i = 0; i < 10_000; i++) {
int id = i;
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100));
return id;
});
}
}
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) {
long fixed = run(Executors.newFixedThreadPool(100));
long virtual = run(Executors.newVirtualThreadPerTaskExecutor());
System.out.println("Fixed pool of 100: " + fixed + " ms");
System.out.println("Virtual threads: " + virtual + " ms");
}
}The fixed pool runs 100 tasks at a time, so it needs 100 rounds of 100 ms, which takes about 10 seconds. The virtual threads all sleep at the same time, so that run usually finishes in well under one second. Exact numbers depend on your machine.
Platform Threads Compared with Virtual Threads
| Feature | Platform thread | Virtual thread |
|---|---|---|
| Backed by | One OS thread, for its whole life | Any carrier thread, only while it runs |
| Cost to create | High (around 1 MB of stack reserved) | Low (a small object on the heap) |
| Practical count | Thousands | Millions |
| Daemon | Your choice | Always |
| Best for | Long-running or CPU-heavy work | Many tasks that spend most of their time blocking |
| Should you pool it? | Yes | No, create one per task |
When Virtual Threads Help and When They Don't
Virtual threads help with I/O-bound work, which is work that spends most of its time waiting on input or output. Web requests, database queries, and calls to other services are I/O-bound.
Virtual threads do not help with CPU-bound work. CPU-bound work keeps the processor busy the whole time, for example resizing images or crunching numbers. The number of CPU cores sets its speed limit. Use a fixed pool sized to about Runtime.getRuntime().availableProcessors() for that kind of work.
Common Mistakes
Pooling virtual threads
A pool exists to reuse threads because platform threads are costly to create. Virtual threads are cheap, so reusing them gains nothing. Don't wrap them in a fixed-size pool. Use one virtual thread per task.
Using the pool size to limit access
Sometimes a pool size quietly protects a resource. For example, a pool of 10 threads means at most 10 database calls at once. With virtual threads that limit is gone. Use a Semaphore instead. A semaphore is an object that hands out a fixed number of permits. A thread has to take a permit before it continues, and it gives the permit back when it is done.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class LimitedVirtual {
public static void main(String[] args) {
Semaphore permits = new Semaphore(10);
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 50; i++) {
int id = i;
executor.submit(() -> {
permits.acquire();
try {
Thread.sleep(200);
System.out.println("Finished call " + id);
} finally {
permits.release();
}
return null;
});
}
}
}
}All 50 virtual threads start, but only 10 can be inside the try block at the same moment. The finally block makes sure the permit is returned even if the work throws.
Pinning inside synchronized
A virtual thread is pinned when it cannot unmount from its carrier. In Java 21, a virtual thread that blocks inside a synchronized block or method stays pinned, so its carrier sits idle. If many threads do this at once, the few carriers fill up and the program stalls. In Java 21 you can avoid this by using java.util.concurrent.locks.ReentrantLock around code that blocks. Java 24 fixed most cases of pinning in synchronized.
Heavy ThreadLocal use
A ThreadLocal stores a separate value for each thread. With a million virtual threads, you get a million copies. Keep the values small, or pass data as method parameters.
Exercise
A program downloads 5,000 web pages. Each download waits about 300 ms for the network. Should it use a fixed pool of 8 platform threads or Executors.newVirtualThreadPerTaskExecutor()? Explain why.
Show answer
Use the virtual thread per-task executor. The work is I/O-bound: each task spends most of its time waiting on the network. With 8 platform threads, only 8 downloads can wait at once. With virtual threads, all 5,000 can wait at the same time, and each one gives up its carrier while it blocks.
Exercise
A teammate writes Executors.newFixedThreadPool(200, Thread.ofVirtual().factory()) so the program never has more than 200 virtual threads. What is wrong with this, and what should they do instead?
Show answer
It pools virtual threads, which gains nothing because virtual threads are cheap to create. If the real goal is to limit how many tasks use a resource at once, they should use newVirtualThreadPerTaskExecutor() and guard the resource with a Semaphore(200).
Exercise
Why might the program below exit without printing anything? Thread.startVirtualThread(() -> System.out.println("hi")); is the only line in main.
Show answer
Virtual threads are always daemon threads, and daemon threads do not keep the program alive. main can end before the virtual thread runs. Save the returned Thread and call join() on it before main ends.