Sub topic 4
Creating Your First Virtual Threads
In the last chapter you learned what a virtual thread is. Now you will create one. Java 21 added a few new methods to the Thread class, and this chapter covers the three you will use most often.
You need JDK 21 or later. Each example is a complete program. Save it in a file named after its class, then run it with java FileName.java.
The Thread.ofVirtual() builder
A builder is an object that lets you set options step by step and then create something. Thread.ofVirtual() returns a builder for virtual threads. You can give the thread a name and then start it with a task.
The task is a lambda. A lambda is a short block of code you can pass around like a value. Here it acts as a Runnable, which is a task that takes no input and returns nothing.
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();
}
}Here is what each part does:
name("hello-vt")gives the thread a name, which helps when you read logs.start(...)creates the thread and starts it right away.Thread.currentThread()returns the thread that is running the code.isVirtual()returnstruefor a virtual thread.join()makesmainwait until the thread finishes.
The output looks something like this:
Running in VirtualThread[#21,hello-vt]/runnable@ForkJoinPool-1-worker-1, virtual = trueThe part after the @ names the carrier thread, which is the platform thread that ran your virtual thread. A later chapter explains carriers.
The Thread.startVirtualThread() shortcut
When you don't need a name or other options, use the shortcut. Thread.startVirtualThread() creates a virtual thread and starts it in one call.
The same program also shows Thread.ofPlatform(). This builder works like ofVirtual() but creates a traditional platform thread. The two builders share the same methods, so switching between them is easy.
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();
}
}Making many named threads with a factory
A ThreadFactory is an object that makes new threads on request. Many libraries and frameworks ask you for a factory instead of a thread. The builder can produce one for you with factory().
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();
}
}name("worker-", 0) sets a prefix and a starting number. The factory names the threads worker-0, worker-1, and so on. Note that newThread() creates the thread but does not start it. You call start() yourself.
Which method should you pick?
| Method | Starts the thread? | Lets you set a name? |
|---|---|---|
| `Thread.ofVirtual().start(task)` | Yes | Yes |
| `Thread.startVirtualThread(task)` | Yes | No |
| `Thread.ofVirtual().unstarted(task)` | No | Yes |
| `factory.newThread(task)` | No | Yes, from the factory |
Creating threads by hand works well for a few tasks. In the next chapter you will run thousands of tasks with an executor that makes the threads for you.
Exercise
You run a program that calls Thread.startVirtualThread(() -> System.out.println("Hi")) as the last line of main, and nothing prints. Why, and how do you fix it?
Show answer
Virtual threads are daemon threads, so the JVM can exit as soon as main finishes, before the virtual thread runs. Keep the returned Thread in a variable and call join() on it at the end of main.
Exercise
Write one line that creates a virtual thread named "loader", without starting it, for the task () -> System.out.println("loading").
Show answer
Thread t = Thread.ofVirtual().name("loader").unstarted(() -> System.out.println("loading"));