0Pricing
Java Academy · Lesson

Combining Futures: allOf and anyOf

Wait for all futures with allOf and race them with anyOf to implement timeout and fallback logic.

Combining Futures: allOf and anyOf is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Combine Futures?

When independent async tasks can run in parallel, you want to wait for all (or the first) to complete before proceeding. allOf and anyOf handle both cases.

allOf: Wait for All Futures

CompletableFuture.allOf(futures...) returns a CompletableFuture<Void> that completes when ALL input futures complete. If any fails, allOf also fails.

CompletableFuture<String> f1 = fetchUserAsync();
CompletableFuture<List<Order>> f2 = fetchOrdersAsync();
CompletableFuture<Double> f3 = fetchBalanceAsync();
CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2, f3);
all.join(); // wait for all three
String user   = f1.join();
List<Order> orders = f2.join();
Double balance = f3.join();

Collecting allOf Results

Since allOf returns Void, collect results by calling join() on each individual future after allOf.join().

List<CompletableFuture<String>> futures = List.of(
    fetchAsync("url1"), fetchAsync("url2"), fetchAsync("url3"));
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
    .thenApply(v -> futures.stream()
        .map(CompletableFuture::join)
        .collect(Collectors.toList()))
    .thenAccept(results -> results.forEach(System.out::println))
    .join();

anyOf: First Completed Wins

CompletableFuture.anyOf(futures...) returns a CompletableFuture<Object> that completes with the result of the first completed future, regardless of type.

CompletableFuture<Object> first = CompletableFuture.anyOf(
    fetchFromCacheAsync(),
    fetchFromDbAsync(),
    fetchFromApiAsync()
);
System.out.println("Fastest result: " + first.join());

anyOf for Timeout Fallback

Race a real computation against a timeout future. Whichever completes first wins — implementing a non-blocking timeout pattern.

CompletableFuture<String> real    = fetchDataAsync();
CompletableFuture<String> timeout = CompletableFuture
    .supplyAsync(() -> {
        try { Thread.sleep(2000); } catch (InterruptedException e) {}
        return "timeout-default";
    });
String result = (String) CompletableFuture.anyOf(real, timeout).join();

orTimeout (Java 9+)

orTimeout(time, unit) completes the future with TimeoutException if it does not finish in time. Cleaner than the manual anyOf-timeout pattern.

CompletableFuture<String> result = fetchDataAsync()
    .orTimeout(3, TimeUnit.SECONDS)
    .exceptionally(ex -> "timeout-default");
System.out.println(result.join());

Parallel HTTP Calls with allOf

Fan out to multiple services in parallel, then join results. Much faster than sequential calls when services are independent.

List<String> urls = List.of(url1, url2, url3);
List<CompletableFuture<String>> futures = urls.stream()
    .map(url -> CompletableFuture.supplyAsync(() -> httpGet(url)))
    .collect(Collectors.toList());
List<String> responses = CompletableFuture
    .allOf(futures.toArray(new CompletableFuture[0]))
    .thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()))
    .join();

Error Handling in allOf

If one future in allOf fails, the returned future fails immediately. Wrap individual futures with exceptionally to prevent one failure from failing the whole batch.

List<CompletableFuture<String>> safe = futures.stream()
    .map(f -> f.exceptionally(ex -> "ERROR: " + ex.getMessage()))
    .collect(Collectors.toList());
CompletableFuture.allOf(safe.toArray(new CompletableFuture[0])).join();

allOf with Different Types

allOf accepts futures of different types. After joining, cast each future's result to the expected type.

CompletableFuture<User> userFuture   = fetchUser(id);
CompletableFuture<Config> configFuture = fetchConfig();
CompletableFuture.allOf(userFuture, configFuture).join();
User   user   = userFuture.join();
Config config = configFuture.join();

Composing allOf and thenApply

Chain thenApply on allOf to aggregate results as soon as all futures complete.

CompletableFuture<String> summary =
    CompletableFuture.allOf(f1, f2, f3)
        .thenApply(v -> "User: " + f1.join() +
                       ", Orders: " + f2.join().size() +
                       ", Balance: " + f3.join());
System.out.println(summary.join());

Thread Pool Considerations

All futures in an allOf / anyOf call can run concurrently. Ensure the thread pool has enough threads or use virtual threads (Java 21+) to avoid starvation.

// With virtual threads (Java 21+):
ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor();
CompletableFuture<String> f = CompletableFuture.supplyAsync(() -> httpGet(url), vt);

Cancellation Propagation

allOf / anyOf do not automatically cancel remaining futures when one completes or is cancelled. Cancel each individually if needed.

CompletableFuture<Object> first = CompletableFuture.anyOf(f1, f2, f3);
first.thenRun(() -> Stream.of(f1, f2, f3).forEach(f -> f.cancel(true)));

Quick Check

What does CompletableFuture.anyOf return?

Recap

allOf waits for all futures (fan-in). anyOf takes the first result (racing). Use orTimeout for timeouts. Wrap individual futures with exceptionally to prevent one failure from failing the batch.

Frequently asked questions

Is the “Combining Futures: allOf and anyOf” lesson free?

Yes — the full text of “Combining Futures: allOf and anyOf” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Combining Futures: allOf and anyOf”?

Wait for all futures with allOf and race them with anyOf to implement timeout and fallback logic. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Combining Futures: allOf and anyOf” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Creating and Completing CompletableFutures
  2. Chaining with thenApply and thenCompose
  3. Combining Futures: allOf and anyOf
  4. Error Handling and Async HTTP Pipeline
← Back to Java Academy