Sub topic 11
Running concurrent subtasks with virtual threads
This chapter assumes you know ExecutorService and Future from java.util.concurrent. It also assumes you have a Spring Boot 3.2+ MVC application on Java 21 with spring.threads.virtual.enabled=true, and that you know what blocking I/O is.
Why fan out inside a request
A request often needs data from several independent sources, such as a user profile and an order list. If you call them one after another, the latency is the sum of both calls. If you run them concurrently, the latency is close to the slower call.
Before virtual threads, this meant a shared thread pool that you had to size and protect from exhaustion. With virtual threads, you can start one thread per subtask and let each one block.
A virtual-thread-per-task executor
Executors.newVirtualThreadPerTaskExecutor() creates an executor that starts a new virtual thread for every submitted task. It has no queue and no pool size.
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.springframework.stereotype.Service;
@Service
class PageService {
String loadPage() throws Exception {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<String> user = executor.submit(this::fetchUser);
Future<String> orders = executor.submit(this::fetchOrders);
return user.get() + " / " + orders.get();
}
}
private String fetchUser() throws InterruptedException {
Thread.sleep(200); // stands in for a blocking HTTP or JDBC call
return "user-42";
}
private String fetchOrders() throws InterruptedException {
Thread.sleep(300);
return "3 orders";
}
}Three details matter here:
ExecutorServiceimplementsAutoCloseablesince Java 19. Thetryblock callsclose(), which waits for all submitted tasks to finish.- Both tasks run at the same time, so
loadPage()takes about 300 ms, not 500 ms. - The request thread is itself virtual, so waiting on
get()does not hold an operating system thread.
Common mistakes
Do not pool virtual threads. A fixed pool of virtual threads brings back the limit you were trying to remove. Create a thread per task and let it end.
Do not treat fan-out as unlimited. Starting 10,000 subtasks that all call one service can overload it. Cap access to the scarce resource with a Semaphore, as described in the chapter on protecting downstream services.
Do not expect request state in subtasks. Each subtask runs on a new thread. A plain ThreadLocal set on the request thread is empty there. Spring's RequestContextHolder and security context holders use thread-locals, so read what you need first and pass it into the task as an argument:
String tenant = currentTenant(); // read on the request thread
Future<String> user = executor.submit(() -> fetchUserFor(tenant));Do not assume failures cancel the other tasks. If user.get() throws ExecutionException, the orders task keeps running, and close() still waits for it. If you need cancellation or timeouts, call future.get(timeout, unit) and future.cancel(true) yourself. Java 21 also has StructuredTaskScope, which handles this. It is a preview API there, so this chapter does not use it.
Choosing a design
| Situation | Approach |
|---|---|
| A few independent blocking calls per request | New executor per call, as above |
| Many tasks against a limited resource | Virtual threads plus a `Semaphore` |
| CPU-heavy subtasks | Platform thread pool sized to the CPU cores |
Exercise
A teammate wraps Executors.newVirtualThreadPerTaskExecutor() in a try-with-resources block, submits two blocking calls, and returns right after the second submit without calling get(). What happens at the end of the block, and why is that useful?
Show answer
close() blocks until both tasks finish, so the method does not return while subtasks are still running. The try block therefore bounds the lifetime of the subtasks. The results are still lost unless the code keeps the Future objects and reads them.