Video in progress
In Java 21, what do you use instead of a parallel stream to call several services in parallel? What does structured concurrency change here?
For I/O fan-out, virtual threads: a separate virtual thread for each call, with plain blocking code. Structured concurrency (preview since Java 21, and still preview in Java 25) additionally binds the child tasks into one block: if one fails, the others are cancelled, and no thread is left "orphaned". A parallel stream is meant for CPU work.
📖 Answer
A parallel stream is unfit for I/O because it is limited by the core count and blocks the shared pool. Virtual threads remove that limit:
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Profile> profile = exec.submit(() -> profileClient.get(userId));
Future<List<Order>> orders = exec.submit(() -> orderClient.recent(userId));
Future<Balance> balance = exec.submit(() -> walletClient.balance(userId));
return new Dashboard(profile.get(), orders.get(), balance.get());
}
It works, but there's a problem: if profile fails, orders and balance still run to the end, spending resources, and the error appears only at get(). You write timeouts and cancellation yourself.
Structured concurrency (StructuredTaskScope) solves this: tasks are created inside a scope, when the scope closes they are all finished or cancelled, and one's failure stops the others. The parent-child relationship also shows up in a thread dump. But the API has been a preview since Java 21 and has changed from version to version (for example, in Java 25 it moved to the new open() style). Enabling a preview in prod code means rewriting on every JDK upgrade. For now I hide it behind a small internal utility or do it with CompletableFuture + a virtual thread executor.
More important questions from an architecture point of view:
- The number of concurrent requests: virtual threads are cheap, but a downstream service isn't. 10,000 parallel calls will take it down. Limiting with a semaphore or a bulkhead is a must.
- Timeouts: separately for each call and for the whole operation.
- Partial result: if the balance service is down, should the dashboard not return at all, or return without the balance field? That is a product decision.
- Pinning: in Java 21–23 blocking inside
synchronizedholds on to the carrier thread. Check old libraries (some JDBC drivers); in Java 24 this is mostly solved.
In short: CPU work is a stream (parallel if needed), I/O fan-out is virtual threads with explicit limits.
Sign up to mark studied questions and save your progress.