Sub topic 3
Meet Virtual Threads
In the last two chapters you saw how a Java program usually does many things at once. It gives each task its own thread. Those threads are expensive, so a server can only have a few thousand of them. When every thread is busy waiting for a database or a web service, new requests have to wait too, even though the CPU has little to do.
Virtual threads fix this. This chapter explains what a virtual thread is, how it differs from the threads you already know, and what it can and cannot do for you. The next chapters show the creation APIs and the internals in more detail.
What a Virtual Thread Is
A virtual thread is a Java thread that the Java Virtual Machine (JVM) manages itself, without giving it a thread from the operating system to keep. The JVM is the program that runs your Java code. The operating system (OS) is the software that runs your computer, such as Linux, Windows, or macOS.
The threads Java has always had are now called platform threads. Each platform thread is a thin wrapper around one OS thread. The OS thread belongs to that Java thread for the thread's whole life. That is why platform threads are costly: the OS has to reserve memory for each one and has to schedule each one.
A virtual thread works differently. It is still a real java.lang.Thread object, and your code runs in it like it runs in any thread. When the virtual thread needs to run code on the CPU, the JVM borrows a platform thread for it. When the virtual thread has to wait, for example for a network reply, the JVM puts it aside and lends that platform thread to another virtual thread.
Here are three new terms:
- A carrier thread is a platform thread that runs virtual threads. It "carries" one virtual thread at a time.
- Mounting means placing a virtual thread on a carrier so it can run.
- Unmounting means taking a waiting virtual thread off its carrier so the carrier is free.
The waiting virtual threads in the diagram use no carrier and no OS thread. They are only small objects in memory. That is the main idea of the whole feature.
A Short History
Virtual threads came out of an OpenJDK project called Project Loom. They first appeared as a preview feature in Java 19 (JEP 425) and again in Java 20 (JEP 436). A preview feature is one you can try but must switch on with a flag, and it may still change. A JEP (JDK Enhancement Proposal) is the document that describes a change to Java.
In Java 21, JEP 444 made virtual threads a final, standard feature. You need no flags. Any JDK 21 or later has them.
Why They Are So Cheap
Memory is the main reason platform threads are expensive. Every thread has a stack, which is the memory that holds the method calls in progress and their local variables.
- A platform thread's stack is set aside by the OS when the thread starts. On 64-bit Linux the default limit is about 1 MB per thread. The thread uses that space whether it needs it or not.
- A virtual thread's stack lives on the Java heap, the same memory area where your normal objects live. It starts small and grows only as deep as your calls actually go. When the thread unmounts, the JVM saves its stack frames as heap objects. When it mounts again, it copies them back.
Creating a virtual thread also skips the call into the OS. To the JVM it is close to creating an ordinary object. A virtual thread that is waiting takes up a few hundred bytes to a few kilobytes, so one JVM can hold hundreds of thousands or even millions of them.
| Property | Platform thread | Virtual thread |
|---|---|---|
| Backed by | One OS thread for its whole life | A borrowed carrier, only while running |
| Stack memory | Reserved up front (about 1 MB by default) | On the heap, grows as needed |
| Cost to create | High, involves the OS | Low, similar to an object |
| Practical number per JVM | Thousands | Millions |
| Scheduled by | The operating system | The JVM |
| Daemon thread | Your choice | Always |
| Priority | Can be changed | Always normal, changes are ignored |
| Good to pool? | Yes, pools save creation cost | No, create a new one per task |
Same Thread API, Same Code Style
You do not have to learn a new programming style. A virtual thread is a Thread, so the methods you know still work: join(), interrupt(), getName(), Thread.currentThread(), Thread.sleep(), and so on. You still write normal step-by-step code that calls a method and waits for the answer.
This kind of code is called blocking code. A blocking call is a method that does not return until its work is done, like reading from a socket. With platform threads, blocking wastes a costly OS thread. With virtual threads, blocking is cheap because the waiting thread unmounts. A later chapter covers this in detail.
Other ways to scale, such as reactive or callback-based libraries, avoid blocking by splitting your logic into many small callbacks. That works, but the code is harder to read and debug. Virtual threads let you keep the simple style and still scale.
Seeing the Difference
The program below runs the same method once in a platform thread and once in a virtual thread. It prints each thread's description and two of its properties. It uses Thread.startVirtualThread(), a shortcut you will study in the next chapter.
public class MeetVirtual {
public static void main(String[] args) throws InterruptedException {
Thread platform = new Thread(MeetVirtual::describe);
platform.start();
platform.join();
Thread virtual = Thread.startVirtualThread(MeetVirtual::describe);
virtual.join();
}
static void describe() {
Thread t = Thread.currentThread();
System.out.println(t + " virtual=" + t.isVirtual() + " daemon=" + t.isDaemon());
}
}Save it as MeetVirtual.java and run it with java MeetVirtual.java on JDK 21 or later. The output looks like this (the numbers may differ):
Thread[#21,Thread-0,5,main] virtual=false daemon=false
VirtualThread[#22]/runnable@ForkJoinPool-1-worker-1 virtual=true daemon=trueThe second line tells you a lot:
VirtualThread[#22]is the virtual thread and its ID. It has no name, because unnamed virtual threads are the default.runnableis its state at that moment.@ForkJoinPool-1-worker-1is the carrier thread it is mounted on right now. That carrier belongs to the JVM's built-in scheduler.
The isVirtual() method was added in Java 21. It is the reliable way to ask whether the current thread is virtual.
A Few Rules That Are Different
Virtual threads behave like platform threads in almost every way, but a few rules are fixed:
- They are always daemon threads. A daemon thread does not keep the JVM alive. When the last non-daemon thread (such as
main) ends, the JVM exits, even if virtual threads are still running. That is why the example callsjoin(). CallingsetDaemon(false)on a virtual thread throws anIllegalArgumentException. - Their priority is always normal. Calling
setPriority()does nothing. - They do not use thread groups.
getThreadGroup()returns a placeholder group named "VirtualThreads". - They are meant to be short-lived and plentiful. You create one for each task and let it end. You do not reuse them.
What Virtual Threads Do Not Do
Many beginners expect virtual threads to be faster. They are not. A virtual thread runs code at the same speed as a platform thread. A single task does not finish sooner.
What virtual threads give you is scale: many more tasks in progress at the same time. That raises throughput, the number of tasks finished per second, when most tasks spend their time waiting.
Here is an example. A server handles requests that each wait 100 milliseconds for a database. With 200 platform threads, it can finish at most about 2,000 requests per second, because it can only wait on 200 at a time. With virtual threads, it can wait on 10,000 at once, so the database or the network becomes the limit and the thread count stops mattering.
If your tasks spend their time calculating on the CPU instead of waiting, more threads do not help. You only have so many cores. A later chapter, "Choosing Virtual Threads: I/O-Bound vs CPU-Bound Work," covers how to decide.
Summary
- A virtual thread is a
java.lang.Threadthat the JVM schedules itself. It does not hold an OS thread for its lifetime. - It runs by mounting on a carrier thread and unmounts when it waits, freeing the carrier for others.
- Its stack lives on the heap and grows as needed, so it costs very little memory. You can have millions.
- It became a standard feature in Java 21 through JEP 444.
- It is always a daemon, always normal priority, and should never be pooled.
- It improves throughput for waiting-heavy work. It does not make code run faster.
Exercise
A program starts one virtual thread that prints a message after sleeping for one second, and then main returns right away without calling join(). What happens, and why?
Show answer
The message most likely never prints. Virtual threads are always daemon threads, so the JVM exits as soon as the main thread (the last non-daemon thread) ends, and it does not wait for the sleeping virtual thread.
Exercise
In the output VirtualThread[#22]/runnable@ForkJoinPool-1-worker-1, what does the part after the @ sign mean?
Show answer
It names the carrier thread that the virtual thread is mounted on at that moment. ForkJoinPool-1-worker-1 is a platform thread belonging to the JVM's built-in virtual thread scheduler.
Exercise
A task spends 5 ms computing on the CPU and finishes. A teammate says switching to virtual threads will make it finish in less than 5 ms. Are they right?
Show answer
No. A virtual thread runs code at the same speed as a platform thread. Virtual threads raise throughput when many tasks spend time waiting, but they do not reduce the time a single CPU-bound task takes.
Exercise
Give two reasons a virtual thread uses far less memory than a platform thread.
Show answer
First, its stack lives on the Java heap and grows only as deep as the calls really go, while a platform thread reserves a large stack (about 1 MB by default) up front. Second, it does not keep an OS thread with its own OS resources, so a waiting virtual thread is only a small heap object.