Sub topic 3
What a virtual thread is
This chapter defines virtual threads as Java 21 (JEP 444) specifies them. It covers how they differ from platform threads, how to create them, and which misconceptions cause the most trouble. It assumes you know Thread, ExecutorService, and java.util.concurrent. It also assumes you know what blocking I/O is, for example a JDBC query or an HTTP call that waits for a reply. Later chapters cover the scheduler details and the Spring Boot property.
The problem a virtual thread solves
A classic Java thread is a platform thread. It is a thin wrapper around one operating system (OS) thread. The OS reserves a stack for it and schedules it. That makes platform threads expensive to create, and a server can only run a few thousand of them. A Spring MVC application uses one thread per request, so that limit becomes a limit on concurrent requests. Most of that time is spent waiting on a database or another service, and the thread holds its memory the whole time.
A virtual thread is a java.lang.Thread that the JVM schedules instead of the OS. It runs your code with the same blocking style as before. When the code blocks on I/O, the JVM parks the virtual thread and frees the underlying OS thread to run something else. The OS thread is called a carrier thread, and the next chapter covers carriers.
The result is that you keep the simple model of one thread per request or task. You can also afford hundreds of thousands of such threads, because each one costs little while it waits.
Platform and virtual threads side by side
Both kinds are instances of Thread. Existing code that takes a Thread, uses Thread.currentThread(), or relies on ThreadLocal keeps working.
| Property | Platform thread | Virtual thread |
|---|---|---|
| Backed by | One OS thread for its whole life | The JVM, which runs it on a carrier thread only while it has work |
| Stack | Reserved by the OS, about 1 MB by default on 64-bit Linux | Stored on the Java heap and grows with use |
| Creation cost | High, so threads are pooled | Low, so you create one per task |
| Practical count | Thousands | Hundreds of thousands or more |
| Daemon status | Chosen by you | Always daemon |
| Priority | Adjustable | Fixed at normal |
| Name | Defaults to `Thread-N` | Defaults to an empty string |
A virtual thread's stack lives on the heap as a stack chunk object. When the thread blocks, the JVM copies its frames into that object. When the thread can run again, the JVM copies the frames back onto a carrier. Stack memory therefore scales with how deep each thread's calls actually go, not with a fixed reservation.
The lifecycle in one picture
The diagram shows what happens when a virtual thread makes a blocking call.
Your code never sees the unmount and mount steps. The call to read() simply returns later, as it would on a platform thread. The JDK made its blocking operations virtual-thread aware to allow this. This covers sockets, Thread.sleep, java.util.concurrent locks and queues, and most of java.nio channels.
Creating virtual threads
There are three common ways to create them. The first is the builder, which gives you control over the name and when the thread starts.
public class VirtualBasics {
public static void main(String[] args) throws Exception {
Thread thread = Thread.ofVirtual().name("worker-1").start(() -> {
Thread current = Thread.currentThread();
System.out.println("virtual=" + current.isVirtual()
+ ", name=" + current.getName()
+ ", daemon=" + current.isDaemon());
});
thread.join();
}
}This prints virtual=true, name=worker-1, daemon=true. The join() call matters. Virtual threads are always daemon threads, so the JVM exits when the last non-daemon thread ends, whether or not your virtual threads have finished.
The second way is the shortcut Thread.startVirtualThread(Runnable). It is equivalent to the builder with no name.
The third way, and the usual one in application code, is an executor that starts a new virtual thread for every task.
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class TenThousandSleepers {
public static void main(String[] args) {
long start = System.nanoTime();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
}));
}
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println("finished in " + millis + " ms");
}
}The program starts 10,000 tasks that each block for one second. On a typical laptop it finishes in a little over one second. A fixed pool of 200 platform threads would need about 50 seconds for the same work, since each batch of 200 waits one second. The try block closes the executor, and close() waits for all submitted tasks to finish.
What does not change
A virtual thread has the same programming model as any other thread. This is deliberate, and it has practical consequences.
- Stack traces,
Thread.currentThread(), interruption, andThreadLocalall work. - Blocking code stays blocking code. You do not need
CompletableFuturechains or callbacks. - Debuggers and profilers that understand
Threadshow virtual threads as well. - A virtual thread runs the same code at the same CPU speed. One call is not faster on a virtual thread.
That last point is the most common misunderstanding. A virtual thread improves throughput when many tasks spend their time waiting. It does not reduce latency for a single request.
What you cannot do
The JDK restricts a few operations that make little sense for virtual threads.
- Calling
setDaemon(false)throwsIllegalArgumentException. setPriorityhas no effect.- You cannot move a virtual thread into a custom
ThreadGroup. All virtual threads share one fixed group namedVirtualThreads. Thread.getAllStackTraces()does not list virtual threads. Use the JSON thread dump instead, which a later chapter covers.
Common errors
- Treating virtual threads as faster threads. A CPU-bound task, such as hashing or image resizing, keeps a carrier busy for its whole run. Having 10,000 virtual threads does not give you more cores. The number of carriers defaults to the number of CPU cores.
- Forgetting that they are daemon threads. A
mainmethod that starts virtual threads and returns will end the program before they finish. Join them or use an executor in atryblock. - Pooling them. See the warning above.
- Assuming unlimited concurrency is safe. With a pool of 200 threads, a database with 20 connections was protected by accident. With virtual threads the pool no longer limits anything, so thousands of tasks can compete for those 20 connections.
- Blocking inside
synchronized. On Java 21, a virtual thread that blocks while holding a monitor cannot unmount, which is called pinning. A later chapter covers how to find it and what to do.
How this connects to Spring
In a Spring MVC application, the embedded server takes a thread from a pool for each request and hands it to your controller. Virtual threads let the server create a new thread per request instead, with no pool limit. Your controller and repository code stays the same. The chapter after next shows the one property that makes this switch.
Exercise
A teammate starts 1,000 virtual threads in main that each call Thread.sleep(500) and then print a line. The program exits with no output. What went wrong, and what are two ways to fix it?
Show answer
Virtual threads are always daemon threads, so the JVM exits as soon as main returns, before the sleeping threads wake up. One fix is to keep the Thread objects and call join() on each. The other is to submit the tasks to Executors.newVirtualThreadPerTaskExecutor() inside a try-with-resources block, because closing the executor waits for all tasks to finish.
Exercise
A service handles each request on a virtual thread and runs a report that hashes large files on every request. After the switch, the service handles no more requests per second than before. Why?
Show answer
Hashing is CPU-bound. The virtual thread never blocks, so it never unmounts, and it holds a carrier thread for the whole computation. The number of carriers is limited by the CPU core count, so total throughput is capped by the cores, exactly as with platform threads. Virtual threads help only when tasks spend most of their time waiting.