Sub topic 5
Running Thousands of Tasks with a Virtual-Thread-per-Task Executor
In the last chapter you made virtual threads one at a time. Real programs often have thousands of small jobs to run at once. Starting each thread by hand and calling join() on every one gets messy fast. An executor handles that work for you.
What an Executor Is
A task is a small piece of work, like "fetch this web page" or "read this file." In Java, a task is usually a Runnable or a Callable written as a lambda.
An executor is an object that takes tasks and runs them on threads for you. You hand it a task with submit(). The executor decides which thread runs it.
Older executors keep a thread pool, which is a fixed group of threads that are reused. Tasks wait in line until a pooled thread is free. Platform threads are costly, so pools keep their number small.
Java 21 adds a different kind of executor:
Executors.newVirtualThreadPerTaskExecutor()This executor has no pool. It creates a brand-new virtual thread for every task you submit. Virtual threads are cheap, so making ten thousand of them is fine.
A Worked Example: 10,000 Sleeping Tasks
This program submits 10,000 tasks. Each task sleeps for one second, then returns its number. Sleeping stands in for slow work such as waiting on a network reply.
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class ManyTasks {
public static void main(String[] args) {
long start = System.nanoTime();
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
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println("All tasks done in " + millis + " ms");
}
}Save it as ManyTasks.java and run it with JDK 21 or later:
java ManyTasks.javaYou should see something close to this:
All tasks done in 1150 msYour number will differ a little. It will still be near one second, not 10,000 seconds.
Reading the Code Line by Line
try (var executor = ...)is a try-with-resources block. It closes the executor automatically when the block ends.IntStream.range(0, 10_000)produces the numbers 0 to 9,999.executor.submit(...)hands one task to the executor. Because the lambda returnsi, Java treats it as aCallable.- When the block ends,
close()runs. It waits until every task has finished. That is why you do not needjoin().
Why It Finishes in About One Second
A sleeping virtual thread does not hold onto a real operating-system thread. While it waits, the JVM lets other virtual threads use that real thread. So all 10,000 tasks sleep at the same time, and they all wake up about one second later. A later chapter explains how this works inside the JVM.
Compare this with a fixed pool of platform threads:
| Executor | Threads used | Approximate time for 10,000 one-second tasks |
|---|---|---|
| `newFixedThreadPool(100)` | 100 platform threads, reused | About 100 seconds |
| `newVirtualThreadPerTaskExecutor()` | 10,000 virtual threads, one per task | About 1 second |
The pool runs only 100 tasks at a time. The other tasks wait in line. The virtual-thread executor never makes tasks wait for a free thread.
Exercises
Exercise
In ManyTasks, what would happen to the total time if you replaced newVirtualThreadPerTaskExecutor() with Executors.newFixedThreadPool(10)?
Show answer
Only 10 tasks could run at once, so the 10,000 tasks would run in 1,000 rounds of one second each. The program would take about 1,000 seconds, roughly 17 minutes.
Exercise
Why does ManyTasks not call join() on any thread, yet still waits for all tasks before printing?
Show answer
The executor is created in a try-with-resources block. When the block ends, close() is called automatically, and close() waits for every submitted task to finish.