- 3.1 Motivation for Virtual Threads
- 3.2 Virtual Thread Execution Model
- 3.3 Using Thread Class to Create Virtual Threads
- 3.4 Using Thread Builders to Create Virtual Threads
- 3.5 Using Thread Factory to Create Threads
- 3.6 Using Thread Executor Services
- 3.7 Scalability of Throughput with Virtual Threads
- 3.8 Best Practices for Using Virtual Threads
- Review Questions
3.5 Using Thread Factory to Create Threads
A thread factory can be used to create threads on demand. Such a factory implements the newThread() method of the ThreadFactory interface that creates and returns an unstarted thread. A thread factory is thread-safe from multiple concurrent threads, as opposed to a thread builder which is not.
Thread builders provide the factory() method that returns a thread factory based on the current state of the builder, such as the thread name to use when creating threads.
ThreadFactory vtf = Thread.ofVirtual().name("VT_", 1).factory(); // (2)
In the code above from Example 3.5, the virtual thread factory (ThreadFactory) obtained from the virtual thread builder (Thread.Builder.OfVirtual) that is returned by the Thread.ofVirtual() method will create unstarted virtual threads whose names will be VT_1, VT_2, and so on.
Unstarted virtual threads are created at (2) by calling the newThread() method of the thread factory and have to be explicitly scheduled to begin execution by calling the start() method of the Thread class:
Thread vt4 = vtf.newThread(task); // VT_1 ... vt4.start();
Using a platform thread factory obtained from a platform thread builder is analogous to using a virtual thread factory obtained from a virtual thread builder.
Example 3.5 Using a Virtual Thread Factory to Create Virtual Threads
package vt;
import java.util.concurrent.ThreadFactory;
public class ThreadFactoryDemo {
public static void main(String[] args) throws InterruptedException {
// Create a task: (1)
Runnable task = () -> System.out.printf("%s: I am on it!%n",
Thread.currentThread());
// Obtain a virtual thread factory using a virtual thread builder:
ThreadFactory vtf = Thread.ofVirtual().name("VT_", 1).factory(); // (2)
// Create virtual threads using the virtual thread factory (3)
Thread vt4 = vtf.newThread(task); // VT_1
Thread vt5 = vtf.newThread(task); // VT_2
vt4.start();
vt5.start();
vt4.join();
vt5.join();
}
}
Probable output from the program:
VirtualThread[#21,vt_5]/runnable@ForkJoinPool-1-worker-2: I am on it! VirtualThread[#20,vt_4]/runnable@ForkJoinPool-1-worker-1: I am on it!
