Sub topic 11
Running concurrent subtasks with virtual threads
This chapter assumes you know ExecutorService and Future, you can read a Spring MVC controller and service, and you have read the earlier chapters on enabling virtual threads and limiting concurrency. The examples use Java 21.
The problem: sequential blocking calls add up
A request handler often needs data from several places. A page might need the user profile, the recent orders, and a recommendation list. If each call blocks for 300 ms and you make them one after another, the handler takes about 900 ms.
The calls do not depend on each other, so they can run at the same time. The total then drops to the slowest single call. Before virtual threads, this meant choosing a shared pool and sizing it. A pool that was too small made requests wait for each other. A pool that was too large wasted memory.
Virtual threads remove that choice. A virtual thread is cheap to create and costs almost nothing while it waits on I/O. You can start a new one for every subtask and let it end when the work is done.
The virtual-thread-per-task executor
Executors.newVirtualThreadPerTaskExecutor() returns an ExecutorService that starts a new virtual thread for every submitted task. It has no queue and no pool size. Since Java 19, ExecutorService implements AutoCloseable. Its close() method waits for all submitted tasks to finish, so a try-with-resources block marks a clear boundary: no subtask outlives the block.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FanOutDemo {
public static void main(String[] args) throws Exception {
long start = System.nanoTime();
String page = loadPage();
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(page + " in about " + millis + " ms");
}
static String loadPage() throws ExecutionException, InterruptedException {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> user = executor.submit(() -> fetchUser());
Future<String> orders = executor.submit(() -> fetchOrders());
return user.get() + " / " + orders.get();
}
}
static String fetchUser() throws InterruptedException {
Thread.sleep(300);
return "user-42";
}
static String fetchOrders() throws InterruptedException {
Thread.sleep(300);
return "3 orders";
}
}Run it and the time is close to 300 ms, not 600 ms. Thread.sleep stands in for a blocking HTTP or JDBC call. When a virtual thread blocks, the JVM unmounts it from its carrier thread, so both waits overlap without tying up operating-system threads.
The sequence looks like this:
Do not pool virtual threads
Pooling is a habit from platform threads, where creation is costly. Virtual threads are meant to be short-lived and disposable. Create one per task and let it end.
A fixed-size pool of virtual threads would bring back the concurrency cap you were trying to remove. If you need a cap, put it on the resource that is scarce. The previous chapter showed how to do that with a Semaphore.
Failures, timeouts, and cancellation
Future.get() throws ExecutionException when the task failed. The original exception is its cause. The executor does not cancel sibling tasks for you. If user.get() fails, the orders task keeps running. The try-with-resources close() then waits for it before the exception leaves the block.
For a request, that is usually not what you want. You want to stop work nobody needs. Add a deadline and cancel on failure:
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
static String loadWithDeadline()
throws InterruptedException, ExecutionException, TimeoutException {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> user = executor.submit(() -> fetchUser());
Future<String> orders = executor.submit(() -> fetchOrders());
try {
String u = user.get(1, TimeUnit.SECONDS);
String o = orders.get(1, TimeUnit.SECONDS);
return u + " / " + o;
} catch (ExecutionException | TimeoutException | InterruptedException e) {
user.cancel(true);
orders.cancel(true);
throw e;
}
}
}cancel(true) interrupts the virtual thread. Blocking calls such as Thread.sleep, BlockingQueue.take, and most NIO operations respond to interruption by throwing. Some older blocking code ignores interrupts. If a subtask does that, close() still waits for it, so the request can outlast your deadline. Check that your HTTP client and JDBC driver honor timeouts of their own, and set those as well.
Each get(1, SECONDS) is a separate wait, so the worst case here is two seconds. If you need one overall deadline, compute the remaining time from a start timestamp before each call.
Waiting for many tasks with invokeAll
When the number of subtasks is not fixed, invokeAll submits a collection of Callable objects and returns when all of them are done:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
static List<String> loadAll(List<String> ids)
throws InterruptedException, ExecutionException {
List<Callable<String>> jobs = new ArrayList<>();
for (String id : ids) {
jobs.add(() -> "details-" + id);
}
List<String> results = new ArrayList<>();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (Future<String> f : executor.invokeAll(jobs)) {
results.add(f.get());
}
}
return results;
}The results come back in the same order as the input. Every future is already complete when invokeAll returns, so get() does not block here. It only unwraps the value or throws the failure.
A fan-out of 500 calls is easy to start and easy to misuse. Without a limit, 500 virtual threads hit the downstream service at once. Wrap the call in a Semaphore as in the previous chapter, or send the work in batches.
Using it inside a Spring service
In a Spring MVC application with spring.threads.virtual.enabled=true, the request handler already runs on a virtual thread. Starting more virtual threads from it is normal. Create the executor inside the method, not as a shared bean, so its lifetime matches the request.
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.springframework.stereotype.Service;
interface UserClient {
String find(String userId) throws Exception;
}
interface OrderClient {
String recent(String userId) throws Exception;
}
record Dashboard(String user, String orders) {}
@Service
class DashboardService {
private final UserClient users;
private final OrderClient orders;
DashboardService(UserClient users, OrderClient orders) {
this.users = users;
this.orders = orders;
}
Dashboard load(String userId) throws Exception {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> user = executor.submit(() -> users.find(userId));
Future<String> recent = executor.submit(() -> orders.recent(userId));
return new Dashboard(user.get(), recent.get());
}
}
}Three things do not carry over to the new threads:
- Thread-bound Spring state.
RequestContextHolder,SecurityContextHolder, and MDC logging fields are stored in thread-locals by default. The subtask threads do not see them. Read what you need on the request thread and pass it as an argument, asuserIdis passed above. - Transactions. A
@Transactionalmethod binds its transaction to the calling thread. Subtasks do not join it. Each subtask that touches the database gets its own connection and its own transaction, which also uses more of the connection pool. - Request-scoped beans. They resolve through the request thread's context. Do not use them inside a subtask.
Structured concurrency
The pattern above has a weakness. Nothing links the subtasks to each other. A failure in one does not stop the others unless you write that code. Java 21 includes StructuredTaskScope to address this, but it is a preview API there. It needs --enable-preview, and its shape may change in later releases. Treat it as a direction to watch. For production code on Java 21, the executor with explicit cancellation is the stable choice.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Sharing one virtual-thread executor and never closing it | Tasks can outlive the request that started them | Create it in try-with-resources per operation |
| Calling `get()` with no timeout | One slow dependency holds the request indefinitely | Use `get(timeout, unit)` and client-level timeouts |
| Ignoring `ExecutionException` causes | You lose the real error | Inspect `getCause()` and rethrow or map it |
| Reading `SecurityContextHolder` inside a subtask | Missing or wrong user | Capture the values first and pass them in |
| Fanning out with no limit | Downstream overload | Add a `Semaphore` or batch the work |
Exercise
A handler starts three subtasks in a try-with-resources block with a virtual-thread-per-task executor. The first call to get() throws ExecutionException because subtask one failed. Subtasks two and three take 10 seconds each. What happens, and how would you avoid the delay?
Show answer
The exception is thrown inside the block, but the executor's close() runs on the way out and waits for subtasks two and three to finish. The request is delayed by about 10 seconds. Catch the exception, call cancel(true) on the other futures so they are interrupted, then rethrow. Also set timeouts on the underlying clients so a blocking call that ignores interrupts still ends.
Exercise
Why should a service method create its own newVirtualThreadPerTaskExecutor() inside try-with-resources, instead of using a singleton bean, and why would you put a Semaphore around a downstream call in the subtask?
Show answer
The per-method executor ties every subtask to the request: close() guarantees that none of them outlives it. Virtual threads cost almost nothing, so creating the executor is cheap. The Semaphore is needed because virtual threads remove the pool cap. Without it, a large fan-out can send many simultaneous calls to a database or service that can only handle a limited number.