Combine tasks: thenCombine, allOf and anyOf
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Tasks that do not depend on each other should start together. A trip planner can ask for the train fare and the hotel price at the same moment, then combine the two answers when both arrive.
thenCombine for two independent results
thenCombine is a CompletableFuture method that waits for two independent futures and joins their two results with a function of two inputs. It returns a new CompletableFuture holding that result.
a.thenCombine(b, fn) waits until two independent futures a and b are both done, then calls fn with both results and returns a future of what fn returns. fn is a BiFunction: two inputs, one output, such as (fare, hotel) -> fare + hotel.
Example 1 · thenCombine: train fare plus hotel price
import java.util.concurrent.CompletableFuture;
public class TripCostDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static int trainFare(String route) { sleep(150); // railway server return 1450; }
static int hotelPrice(String city) { sleep(150); // hotel booking server return 2200; }
public static void main(String[] args) { CompletableFuture<Integer> fare = CompletableFuture.supplyAsync(() -> trainFare("Delhi-Jaipur")); CompletableFuture<Integer> hotel = CompletableFuture.supplyAsync(() -> hotelPrice("Jaipur")); System.out.println("Both requests sent");
CompletableFuture<String> total = fare.thenCombine(hotel, (f, h) -> "Fare " + f + " + hotel " + h + " = Rs " + (f + h)); System.out.println(total.join()); }}Both requests sent Fare 1450 + hotel 2200 = Rs 3650
What this code does
fareandhotelstart running on two pool threads straight away, so the two 150 ms waits overlap.thenCombinecalls theBiFunctiononce both numbers are ready, withffromfareandhfromhotel.
Both tasks are already running before thenCombine is called; it only says what to do when both have finished. Compare this with thenCompose, where the second call cannot start until the first result is known.
fn is never called. Lesson 6 of this module shows how to recover.allOf and collecting a list of results
CompletableFuture.allOf(f1, f2, ...) returns a CompletableFuture<Void> that completes when every given future is done. It works for any number of futures, which thenCombine does not.
Example 2 · allOf: marks from four subject servers
import java.util.List;import java.util.concurrent.CompletableFuture;
public class AllMarksDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static CompletableFuture<Integer> marks(String subject, int value, long delayMs) { return CompletableFuture.supplyAsync(() -> { sleep(delayMs); // each subject has its own server return value; }); }
public static void main(String[] args) { List<String> subjects = List.of("Maths", "Physics", "Chemistry", "English"); List<CompletableFuture<Integer>> futures = List.of( marks("Maths", 91, 160), marks("Physics", 78, 40), marks("Chemistry", 84, 120), marks("English", 88, 80));
CompletableFuture<Void> all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); all.join(); // wait for every subject
List<Integer> results = futures.stream().map(CompletableFuture::join).toList(); for (int i = 0; i < subjects.size(); i++) { System.out.println(subjects.get(i) + ": " + results.get(i)); } System.out.println("Total: " + results.stream().mapToInt(Integer::intValue).sum() + " / 400"); }}Maths: 91 Physics: 78 Chemistry: 84 English: 88 Total: 341 / 400
What this code does
- Physics finishes first and Maths last, but the results print in list order:
map(CompletableFuture::join)reads each future in the order of the list. - After
all.join()every future is complete, so thejoin()calls in the stream return at once without waiting.
Example 3 · A reusable helper: from List of futures to a future of List
import java.util.List;import java.util.concurrent.CompletableFuture;
public class AllAsListDemo { static <T> CompletableFuture<List<T>> allAsList(List<CompletableFuture<T>> futures) { return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) .thenApply(ignored -> futures.stream().map(CompletableFuture::join).toList()); }
static CompletableFuture<String> pnrStatus(String pnr) { return CompletableFuture.supplyAsync(() -> pnr + ": " + (pnr.endsWith("0") ? "CNF" : "WL 4")); }
public static void main(String[] args) { List<String> pnrs = List.of("4521897630", "4521897631", "4521897640"); List<CompletableFuture<String>> checks = pnrs.stream().map(p -> pnrStatus(p)).toList();
CompletableFuture<List<String>> report = allAsList(checks); report.thenAccept(lines -> lines.forEach(System.out::println)).join(); }}4521897630: CNF 4521897631: WL 4 4521897640: CNF
What this code does
allAsListturnsList<CompletableFuture<T>>intoCompletableFuture<List<T>>. ThethenApplyruns only afterallOfis done, so itsjoin()calls never block.- Because the result is a normal future, the caller can keep chaining with
thenAcceptinstead of joining each check by hand.
The Void means allOf carries no results. Once it is done, call join() on each original future: they are all complete, so these calls return at once. Mapping the list with CompletableFuture::join keeps the results in list order, whatever order the tasks finished in. allOf takes an array, so a List of futures is passed as list.toArray(new CompletableFuture[0]).
anyOf for the fastest answer
CompletableFuture.anyOf(f1, f2, ...) returns a future that completes as soon as any one of the given futures completes, with that future's result. Use it when several sources give the same answer and you want the quickest, such as mirror servers for exam results.
Example 4 · anyOf: take the fastest mirror server
import java.util.concurrent.CompletableFuture;
public class FastestMirrorDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static CompletableFuture<String> mirror(String name, long delayMs) { return CompletableFuture.supplyAsync(() -> { if (delayMs > 0) { sleep(delayMs); } return "Result PDF from " + name; }); }
public static void main(String[] args) { CompletableFuture<String> a = mirror("Mirror A", 200); CompletableFuture<String> b = mirror("Mirror B", 0); CompletableFuture<String> c = mirror("Mirror C", 120);
CompletableFuture<Object> first = CompletableFuture.anyOf(a, b, c); String pdf = (String) first.join(); System.out.println(pdf); System.out.println("Mirror A finished yet? " + a.isDone()); }}Result PDF from Mirror B Mirror A finished yet? false
What this code does
- Mirror B answers at once, long before the others, so
anyOfcompletes with its result. The(String)cast is needed becauseanyOfreturnsCompletableFuture<Object>. - Mirror A is still sleeping when
mainprints:anyOfdoes not stop the slower tasks. Here they are dropped when the JVM exits.
Its type is CompletableFuture<Object>, because the futures could hold different types. You must cast the result: String first = (String) anyOf(a, b).join();. The slower tasks are not stopped; they keep running and their results are ignored. If the first future to finish failed, anyOf fails with that error, even if a slower one would have succeeded.
Total time of parallel versus sequential calls
Sequential calls run one after another, so the total time is the sum of all the calls. Parallel calls run at the same time, so the total is about the time of the slowest call.
Example 5 · Sequential versus parallel: timing three calls
import java.util.concurrent.CompletableFuture;
public class ParallelTimeDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static int call(String service, long ms, int value) { sleep(ms); // pretend network call return value; }
static long roundTo50(long ms) { return Math.round(ms / 50.0) * 50; }
public static void main(String[] args) { long start = System.currentTimeMillis(); int a = CompletableFuture.supplyAsync(() -> call("fare", 200, 1450)).join(); int b = CompletableFuture.supplyAsync(() -> call("baggage", 150, 600)).join(); int c = CompletableFuture.supplyAsync(() -> call("insurance", 100, 45)).join(); long seq = System.currentTimeMillis() - start; System.out.println("Sequential: Rs " + (a + b + c) + " in about " + roundTo50(seq) + " ms");
start = System.currentTimeMillis(); CompletableFuture<Integer> fa = CompletableFuture.supplyAsync(() -> call("fare", 200, 1450)); CompletableFuture<Integer> fb = CompletableFuture.supplyAsync(() -> call("baggage", 150, 600)); CompletableFuture<Integer> fc = CompletableFuture.supplyAsync(() -> call("insurance", 100, 45)); int total = fa.thenCombine(fb, Integer::sum).thenCombine(fc, Integer::sum).join(); long par = System.currentTimeMillis() - start; System.out.println("Parallel: Rs " + total + " in about " + roundTo50(par) + " ms"); }}Sequential: Rs 2095 in about 500 ms Parallel: Rs 2095 in about 200 ms
What this code does
- In the first half each
join()waits before the next task starts, so the times add up: 200 + 150 + 100 = 450 ms, plus a little for starting threads. In the second half all three start first and overlap, so the total is close to the slowest call, 200 ms. - Times change a little from run to run and machine to machine, which is why this is a sample. The gap between the two lines is what stays.
Three calls of 200, 150 and 100 ms take about 450 ms one by one, but about 200 ms together. This only works when the pool has enough free threads: on a 2-thread pool, three calls still need two rounds. The usual mistake is supplyAsync(a).join() followed by supplyAsync(b).join(). Each join() waits before the next task starts, so the code looks async but runs sequentially. Start every task first, then wait.
Next step
Check your understanding
12 quick questions