Sub topic 5
Running Thousands of Tasks with a Virtual-Thread-per-Task Executor
In the last chapter you created virtual threads one at a time with Thread.ofVirtual() and Thread.startVirtualThread(). That is fine for two or three threads. Real programs often need to run hundreds or thousands of small jobs at once, though, and starting and joining each thread by hand gets messy fast.
This chapter shows the tool Java gives you for that job: Executors.newVirtualThreadPerTaskExecutor(). You will learn what an executor is, how this one works, how to get results and errors back from your tasks, and why it handles thousands of waiting tasks without trouble.
What an Executor Is
A task is a small piece of work you want done, such as "fetch this web page" or "look up this customer." In Java, a task is usually a lambda that implements Runnable (returns nothing) or Callable (returns a value).
An executor is an object that runs tasks for you. You hand it a task, and it decides which thread runs it. In Java, most executors implement the ExecutorService interface. That interface gives you methods such as:
submit(task), which hands a task to the executor and returns aFuture.invokeAll(tasks), which hands over a whole list of tasks and waits for all of them.close(), which stops accepting new tasks and waits for the running ones to finish.
A Future is a receipt for a task. It stands for a result that may not exist yet. You call get() on it to wait for the task and read its result.
Two Kinds of Executors
Before Java 21, the most common executor was a thread pool. A thread pool is a fixed group of threads that get reused. You create it with something like Executors.newFixedThreadPool(10). Tasks wait in a queue until one of the 10 threads is free.
Thread pools exist because platform threads are expensive. You reuse a few of them so that you never create too many.
Virtual threads are cheap, so reuse is not needed. Executors.newVirtualThreadPerTaskExecutor() creates an executor that starts a brand new virtual thread for every task you submit. There is no pool and no queue of waiting tasks. Each task starts right away on its own thread, and that thread ends when the task ends.
| Feature | Fixed thread pool | Virtual-thread-per-task executor |
|---|---|---|
| How it is created | `Executors.newFixedThreadPool(n)` | `Executors.newVirtualThreadPerTaskExecutor()` |
| Kind of thread | Platform threads | Virtual threads |
| Number of threads | Exactly `n`, reused | One new thread per task |
| What happens to extra tasks | They wait in a queue | They start at once |
| Good for | A small number of CPU-heavy tasks | Many tasks that spend time waiting |
Your First Ten Thousand Tasks
Here is a program that runs 10,000 tasks. Each task sleeps for one second, which stands in for waiting on a network or a database.
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");
}
}Save it as ManyTasks.java and run it with java ManyTasks.java on JDK 21 or later. It prints All tasks done after about one second.
Here is what each part does:
try (var executor = ...)is a try-with-resources statement. It is a block that automatically callsclose()on the object when the block ends. Since Java 19,ExecutorServicesupports this.IntStream.range(0, 10_000)produces the numbers 0 to 9,999.executor.submit(...)hands over one task. Because the lambda returns a value (i), Java treats it as aCallable. ACallableis allowed to throw checked exceptions, soThread.sleepneeds no extratry/catchhere.- When the
tryblock ends,close()runs. It waits until all 10,000 tasks have finished.
Why one second and not 10,000 seconds? All 10,000 virtual threads sleep at the same time. A sleeping virtual thread does not hold onto an operating system thread, so the JVM can keep thousands of them waiting at very low cost. A later chapter explains exactly how that works.
Seeing the Difference in Time
To feel the difference, compare a fixed pool of 10 platform threads with the virtual-thread-per-task executor. Both run 1,000 tasks that each sleep for 100 milliseconds.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompareExecutors {
static long runTasks(ExecutorService executor) {
long start = System.nanoTime();
try (executor) {
for (int i = 0; i < 1_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(100));
return null;
});
}
}
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) {
long pooled = runTasks(Executors.newFixedThreadPool(10));
System.out.println("Fixed pool of 10: " + pooled + " ms");
long virtual = runTasks(Executors.newVirtualThreadPerTaskExecutor());
System.out.println("Virtual per task: " + virtual + " ms");
}
}A typical run prints something like this:
Fixed pool of 10: 10087 ms
Virtual per task: 121 msThe fixed pool can only run 10 tasks at a time. 1,000 tasks of 100 ms each, 10 at a time, need about 10 seconds. The virtual executor runs all 1,000 at once, so the whole job takes about as long as one task.
try (executor) works because executor is a method parameter that never changes. Java lets you put an existing variable like that inside the parentheses of a try-with-resources.
Getting Results Back
Often you want the answers your tasks produce. Keep the Future objects that submit returns, then call get() on each one.
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CollectResults {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Future<Integer>> futures = new ArrayList<>();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000; i++) {
int n = i;
futures.add(executor.submit(() -> {
Thread.sleep(Duration.ofMillis(200));
return n * 2;
}));
}
long total = 0;
for (Future<Integer> future : futures) {
total += future.get(); // waits for this task if it is not done yet
}
System.out.println("Total: " + total);
}
}
}This prints Total: 999000 after about 200 milliseconds. Note the line int n = i;. A lambda can only use local variables that never change, and the loop variable i changes on every pass. Copying it into n gives each task its own fixed value.
When a Task Fails
If a task throws an exception, the executor does not crash and does not print anything. It stores the exception inside the Future. When you call get(), Java throws an ExecutionException, and the original error is available from getCause().
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TaskFailure {
public static void main(String[] args) throws InterruptedException {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> future = executor.submit(() -> {
if (true) {
throw new IllegalStateException("database not reachable");
}
return "ok";
});
try {
System.out.println(future.get());
} catch (ExecutionException e) {
System.out.println("Task failed: " + e.getCause().getMessage());
}
}
}
}This prints Task failed: database not reachable. The if (true) is there only so the compiler accepts the return line after the throw.
Naming the Threads
Thread names show up in logs and thread dumps, so names can help you find problems. If you want named virtual threads, combine the builder from the last chapter with Executors.newThreadPerTaskExecutor, which accepts a thread factory. A thread factory is an object that makes new threads on request.
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class NamedExecutor {
public static void main(String[] args) {
ThreadFactory factory = Thread.ofVirtual().name("worker-", 0).factory();
try (var executor = Executors.newThreadPerTaskExecutor(factory)) {
for (int i = 0; i < 3; i++) {
executor.submit(() ->
System.out.println(Thread.currentThread().getName()));
}
}
}
}This prints worker-0, worker-1, and worker-2, in some order. The order can change from run to run because the threads run at the same time.
Common Mistakes
- Putting virtual threads in a pool. Wrapping virtual threads in a fixed-size pool throws away their main benefit. Create one per task. If you need to limit how many tasks touch something at once, a later chapter shows a better tool.
- Expecting speed for heavy computing. The big gains come from tasks that wait. Tasks that keep the CPU busy the whole time do not finish faster just because there are more threads.
- Ignoring futures. As shown above, unchecked futures hide errors.
- Forgetting
close(). Always use try-with-resources so the executor waits for its tasks.
Exercise
You submit 5,000 tasks to Executors.newFixedThreadPool(50). Each task sleeps for 2 seconds. About how long does the whole job take? How long would it take with Executors.newVirtualThreadPerTaskExecutor()?
Show answer
The fixed pool runs 50 tasks at a time, so it needs 5,000 / 50 = 100 rounds of 2 seconds, about 200 seconds. The virtual-thread-per-task executor starts all 5,000 tasks at once, so the job takes about 2 seconds.
Exercise
A teammate writes a loop that calls executor.submit(task) for 100 tasks and never stores the returned Future objects. Some tasks throw exceptions, but nothing appears in the output. Why, and how do you fix it?
Show answer
The executor stores each task's exception inside its Future instead of printing it. Because nobody calls get(), the exceptions are never seen. Fix it by keeping the futures in a list and calling get() on each one, catching ExecutionException and reading getCause().
Exercise
Why does the CollectResults program copy the loop variable into "int n = i;" before using it in the lambda?
Show answer
A lambda can only use local variables that are final or effectively final. The loop variable i changes on every pass, so it cannot be used directly. Copying it into n, which never changes, gives each task its own fixed value.