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

Practical Patterns: Parallel API Calls and Timeouts

Apply allOf and anyOf to real scenarios like parallel REST calls, timeout implementations, and failover strategies.

Practical Patterns: Parallel API Calls and Timeouts

You'll learn how to apply allOf and anyOf to real-world scenarios like parallel REST calls, timeout implementations, and failover strategies.

The Real-World Challenge

Now that you understand allOf and anyOf, let's see how they solve actual production problems: fetching data from multiple services simultaneously, racing requests with timeouts, and building resilient failover systems.

Pattern 1: Parallel API Calls with allOf

When you need data from multiple independent sources (e.g., user profile, order history, recommendations), use allOf to fire all requests at once and wait for all to complete:

CompletableFuture<User> userFuture = fetchUser(userId);
CompletableFuture<Orders> ordersFuture = fetchOrders(userId);
CompletableFuture<List<Product>> recsFuture = fetchRecommendations(userId);

CompletableFuture<Void> allDone = CompletableFuture.allOf(
    userFuture, ordersFuture, recsFuture
);

allDone.thenRun(() -> {
    User user = userFuture.join();
    Orders orders = ordersFuture.join();
    List<Product> recs = recsFuture.join();
    // Combine results into dashboard
});

Pattern 2: Timeout Implementation with anyOf

Race your actual task against a timeout future to prevent hanging:

CompletableFuture<String> apiCall = callExternalService();
CompletableFuture<String> timeout = timeoutAfter(5, TimeUnit.SECONDS);

CompletableFuture<Object> result = CompletableFuture.anyOf(apiCall, timeout);
result.thenAccept(r -> {
    if (r instanceof String) {
        // Success case
    } else {
        // Timeout occurred
    }
});

Pattern 3: Failover Strategy with anyOf

Call multiple backup services simultaneously; use whichever responds first:

CompletableFuture<Data> primary = callPrimaryService();
CompletableFuture<Data> backup = callBackupService();

CompletableFuture.anyOf(primary, backup)
    .thenAccept(result -> processData((Data) result));

Key Takeaway: Use allOf for aggregating parallel operations and anyOf for racing scenarios like timeouts and failover—patterns that make distributed systems faster and more resilient.