CompletableFuture AllOf Fan Out Join
Fan out calls with CompletableFuture.supplyAsync, synchronize with allOf, then collect every result in order with the allOf-join trick.
Code
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class PriceAggregator {
record Quote(String vendor, int cents) {}
public static void main(String[] args) throws Exception {
List<String> vendors = List.of("acme", "bulk", "prime");
// 每家供应商一个异步任务:supplyAsync 立即返回,互不阻塞
List<CompletableFuture<Quote>> quotes = vendors.stream()
.map(vendor -> CompletableFuture.supplyAsync(
() -> new Quote(vendor, vendor.length() * 100)))
.toList();
// allOf 只做汇合点:等全部完成,自身不携带任何单个结果
CompletableFuture<Void> barrier =
CompletableFuture.allOf(quotes.toArray(new CompletableFuture[0]));
// 标准写法:join barrier 后再逐个 join,结果顺序与 vendors 一致
Quote[] ordered = barrier.thenApply(v -> quotes.stream()
.map(CompletableFuture::join)
.toArray(Quote[]::new))
.join();
for (Quote quote : ordered) {
System.out.println(quote.vendor() + " -> " + quote.cents());
}
}
}How it works
CompletableFuture AllOf Fan Out Join keeps everything in the classes PriceAggregator and Quote.
Iteration happens inside for (Quote quote : ordered) — everything outside it runs once. The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Key statements
List<CompletableFuture<Quote>> quotes = vendors.stream()
.map(vendor -> CompletableFuture.supplyAsync(
() -> new Quote(vendor, vendor.length() * 100)))
.toList();
.map(CompletableFuture::join)
.toArray(Quote[]::new))
.join();
CompletableFuture.allOf(quotes.toArray(new CompletableFuture[0]));
FAQ
- How do you run CompletableFuture AllOf Fan Out Join?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.