Sub topic 4
Creating Your First Virtual Threads
In the last chapter you learned what a virtual thread is. In this chapter you will write code that creates one. You will see three ways to make virtual threads, how to give them names, and a few small rules that often surprise people who are new to them.
You need JDK 21 or later. Virtual threads became a final, standard feature in Java 21 (JEP 444), so you do not need any special flags.
The Thread.Builder: one API for both kinds of threads
Java 21 added a new way to make threads called a builder. A builder is an object that collects settings, such as a name, and then creates the thing you asked for.
There are two builders:
Thread.ofVirtual()gives you a builder for virtual threads.Thread.ofPlatform()gives you a builder for platform threads. These are the classic Java threads, each backed by one operating system thread.
Both builders share the same methods. Once you know one, you know the other. Here are the methods you will use most:
| Method | What it does |
|---|---|
| `name(String)` | Gives the thread a fixed name |
| `name(String prefix, long start)` | Names threads `prefix0`, `prefix1`, and so on |
| `start(Runnable)` | Creates the thread and starts it right away |
| `unstarted(Runnable)` | Creates the thread but does not start it |
| `factory()` | Returns a `ThreadFactory` that makes threads with these settings |
A Runnable is a small piece of code with no inputs and no result. You usually write it as a lambda, like () -> System.out.println("hi").
Your first virtual thread
This program creates one virtual thread, names it, starts it, and waits for it to finish.
public class HelloVirtual {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.ofVirtual().name("hello-vt").start(() -> {
Thread current = Thread.currentThread();
System.out.println("Running in " + current + ", virtual = " + current.isVirtual());
});
t.join();
}
}Save it as HelloVirtual.java and run it:
java HelloVirtual.javaYou will see output like this. The numbers may differ on your machine:
Running in VirtualThread[#21,hello-vt]/runnable@ForkJoinPool-1-worker-1, virtual = trueHere is what each part does:
Thread.ofVirtual()makes a builder for virtual threads..name("hello-vt")sets the thread's name..start(...)creates the thread and starts running the lambda.Thread.currentThread()returns the thread that is running this code right now.isVirtual()returnstruefor a virtual thread andfalsefor a platform thread.t.join()makesmainwait until the thread is done.
Look at the printed text again. The part after @, ForkJoinPool-1-worker-1, is the carrier thread. A carrier thread is a platform thread that runs your virtual thread for a while. A later chapter explains carriers in detail. For now, just notice that a virtual thread runs on top of a platform thread.
The shortcut: Thread.startVirtualThread()
If you do not need a name or other settings, there is a one-line shortcut. This program shows it next to the platform builder, so you can compare them:
public class StartVirtual {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.startVirtualThread(() -> System.out.println("Hello from a virtual thread"));
t.join();
Thread platform = Thread.ofPlatform().start(() -> System.out.println("Hello from a platform thread"));
platform.join();
}
}Output:
Hello from a virtual thread
Hello from a platform threadThread.startVirtualThread(task) does exactly the same thing as Thread.ofVirtual().start(task). Use whichever reads better.
The two halves of this program look almost the same. That is the point of the design. Switching between thread kinds is a one-word change, from ofPlatform to ofVirtual.
Creating now, starting later: unstarted()
Sometimes you want to build a thread first and start it later. Use unstarted() for that:
public class StartLater {
public static void main(String[] args) throws InterruptedException {
Thread t = Thread.ofVirtual()
.name("later")
.unstarted(() -> System.out.println("Now I run in " + Thread.currentThread().getName()));
System.out.println("State before start: " + t.getState());
t.start();
t.join();
System.out.println("State after join: " + t.getState());
}
}Output:
State before start: NEW
Now I run in later
State after join: TERMINATEDgetState() tells you where a thread is in its life. NEW means "created but not started." TERMINATED means "finished." Virtual threads use the same states as platform threads.
Many threads with names: a ThreadFactory
A ThreadFactory is a standard Java interface with one method, newThread(Runnable). Many libraries and frameworks ask you for a factory so they can make threads themselves. The builder can produce one for you:
import java.util.concurrent.ThreadFactory;
public class NamedFactory {
public static void main(String[] args) throws InterruptedException {
ThreadFactory factory = Thread.ofVirtual().name("worker-", 0).factory();
Thread a = factory.newThread(() -> System.out.println(Thread.currentThread().getName()));
Thread b = factory.newThread(() -> System.out.println(Thread.currentThread().getName()));
a.start();
b.start();
a.join();
b.join();
}
}Output (the order of the two lines can change from run to run):
worker-0
worker-1The call name("worker-", 0) means "use the prefix worker- and count up from 0." Each new thread gets the next number. Good names help a lot when you read logs or thread dumps later.
Note two details:
newThread()returns an unstarted thread. You must callstart()yourself.- The two threads run at the same time, so the lines may print in either order. This is normal for threads.
Small rules that surprise beginners
Virtual threads behave like normal threads almost everywhere. A few settings work differently.
Virtual threads are always daemon threads
A daemon thread is a background thread. The JVM does not wait for daemon threads before it exits. Every virtual thread is a daemon thread, and you cannot change that.
This matters if you forget join():
public class ForgotJoin {
public static void main(String[] args) {
Thread.startVirtualThread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
return;
}
System.out.println("You may never see this line");
});
System.out.println("main is done");
}
}Most likely, this prints only main is done. The main method ends, no non-daemon threads are left, and the JVM exits before the virtual thread wakes up. The fix is to keep the returned Thread and call join() on it.
Calling setDaemon(false) on a virtual thread throws an IllegalArgumentException.
Priority is fixed
Every virtual thread has priority Thread.NORM_PRIORITY (the value 5). Calling setPriority() on a virtual thread does nothing. The virtual thread scheduler does not use priorities.
Exceptions still need handling
If the code in a virtual thread throws an exception and nothing catches it, the thread ends. Java prints the stack trace, just as it does for a platform thread. The main thread does not see the exception, and join() returns normally. If you need to know whether a task failed, catch the exception inside the task, or use an executor that returns a Future (next chapter).
Here is a quick summary
| Feature | Platform thread | Virtual thread |
|---|---|---|
| Created by `new Thread(...)` | Yes | No |
| Builder | `Thread.ofPlatform()` | `Thread.ofVirtual()` |
| `isVirtual()` | `false` | `true` |
| Daemon | Your choice | Always yes |
| Priority | Can change | Always 5 |
| Type | `Thread` | `Thread` |
Checking the cost yourself
The last chapter said virtual threads are cheap. You can see this with a short test. This program starts 100,000 virtual threads that each sleep for one second:
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
public class HundredThousand {
public static void main(String[] args) throws InterruptedException {
long begin = System.currentTimeMillis();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 100_000; i++) {
threads.add(Thread.startVirtualThread(() -> {
try {
Thread.sleep(Duration.ofSeconds(1));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}
for (Thread t : threads) {
t.join();
}
System.out.println("Done in " + (System.currentTimeMillis() - begin) + " ms");
}
}On a typical laptop this finishes in a little over one second. If you change startVirtualThread to Thread.ofPlatform().start, the program becomes much slower, and on many machines it fails with an OutOfMemoryError saying it cannot create a native thread.
Exercises
Exercise
What is the difference between Thread.ofVirtual().start(task) and Thread.ofVirtual().unstarted(task)?
Show answer
start(task) creates the virtual thread and starts running it immediately. unstarted(task) creates the thread in the NEW state, and nothing runs until you call start() on it.
Exercise
A teammate writes new Thread(() -> work()).start() and says it uses a virtual thread because the project runs on JDK 21. Are they right?
Show answer
No. The Thread constructor always creates a platform thread, on any JDK version. To get a virtual thread they must use Thread.ofVirtual(), Thread.startVirtualThread(), or a virtual-thread executor.
Exercise
A program calls Thread.startVirtualThread(...) with a task that sleeps for 2 seconds and then prints a message. The main method returns right after starting the thread. Why does the message often never appear, and how do you fix it?
Show answer
Virtual threads are always daemon threads, so the JVM exits when main finishes and does not wait for them. Keep the returned Thread and call join() on it before main returns.
Exercise
Write one line that creates a ThreadFactory producing virtual threads named job-1, job-2, job-3, and so on.
Show answer
ThreadFactory factory = Thread.ofVirtual().name("job-", 1).factory();