Multithreading: CompletableFuture.allOf waits on a whole batch

allOf takes any number of futures and returns a CompletableFuture<Void> that completes once every one of them has finished, though it carries none of their values itself. Each original future's own get() still returns its individual result afterwards.

Code
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 1);
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 2);
CompletableFuture<Integer> f3 = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2, f3);
all.join();
int total = f1.get() + f2.get() + f3.get();
System.out.println("All futures done, total: " + total);
Output
All futures done, total: 6
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms