Course contentsShow
← Java
Lesson 2858 of 2,87051. CompletableFutureFree lesson

CompletableFuture.anyOf: Racing Multiple Futures

Understand anyOf's behavior: completing when the first future completes and returning its result as Object.

CompletableFuture.anyOf: Racing Multiple Futures

You'll learn how anyOf races multiple futures and returns the first one to finish, giving you its result as an Object.

The Racing Concept

While allOf waits patiently for every future to complete, anyOf is the opposite—it's a race where only the fastest matters. The moment any future completes (successfully or exceptionally), anyOf completes immediately with that result.

Think of it like multiple delivery drivers racing to your door. You only care about whoever arrives first—you don't wait for the others.

Behavior and Return Type

The signature is:

CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)

Notice the return type: CompletableFuture<Object>. Since the competing futures might have different result types (String, Integer, etc.), Java uses Object as the common denominator. You'll need to cast the result if you know its type.

Key behavior points:

  • Completes when the first future completes (not all of them)
  • Returns the winner's result as Object
  • Other futures continue running in the background (they're not cancelled)
  • If the first future completes exceptionally, anyOf completes exceptionally too

Basic Example Structure

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Result A");
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 42);

CompletableFuture<Object> winner = CompletableFuture.anyOf(future1, future2);

winner.thenAccept(result -> {
    System.out.println("First result: " + result); // Could be "Result A" or 42
});

Key Takeaway: CompletableFuture.anyOf completes as soon as any of its input futures finishes, returning that future's result as Object—perfect for racing scenarios where you only need the fastest response.