Sub topic 2
Running Thousands of Tasks with a Virtual-Thread-per-Task Executor
One Virtual Thread for Every Task
An executor is a Java object that runs tasks for you. Executors.newVirtualThreadPerTaskExecutor() creates an executor that starts a new virtual thread for each task you submit. You never reuse threads or size a pool.
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class ManyTasks {
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i ->
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
}));
} // close() waits for all submitted tasks to finish
System.out.println("All tasks done");
}
}This program runs 10,000 tasks. Each one sleeps for one second, and the whole program finishes in about one second. The try (...) block is a try-with-resources block, which closes the executor at the end. Closing it waits for every task to finish.
Under the Hood: Carrier Threads and Mounting
A carrier thread is a platform thread that runs virtual threads. The JVM keeps a small group of carriers, usually one per CPU core. Mounting is when a virtual thread is placed on a carrier to run. When the virtual thread blocks, it unmounts: it steps off the carrier and frees that carrier for another virtual thread.
Blocking Is Cheap Again: Sleep, I/O, and Locks
Blocking means waiting for something, such as a timer, a network reply, a file, or a lock. With platform threads, a blocked thread wastes a costly operating-system thread. A blocked virtual thread just unmounts, so waiting costs very little. You can write plain, step-by-step code that calls Thread.sleep, reads from a socket, or takes a ReentrantLock.
Choosing Virtual Threads: I/O-Bound vs CPU-Bound Work
| Kind of work | What it does most | Do virtual threads help? |
|---|---|---|
| I/O-bound | Waits on networks, disks, databases | Yes, many tasks can wait at once |
| CPU-bound | Calculates without waiting | No, the CPU cores are already busy |
Exercise
A program resizes 10,000 images, using the CPU the whole time. Will switching to virtual threads make it much faster?
Show answer
No. The work is CPU-bound, so the tasks rarely block and unmount. The number of CPU cores limits speed, and virtual threads do not add cores.