CompletableFuture for Concurrent Composition

Uses CompletableFuture to compose asynchronous operations with thenApply, thenCompose, thenCombine, and exception handling for non-blocking pipelines.

JavaData Fetching

Code

snippet
import java.util.concurrent.*;
import java.util.List;

public class CompletableFutureExample {

    static CompletableFuture<String> fetchUserName(int id) {
        return CompletableFuture.supplyAsync(() -> {
            sleep(200);
            return "User" + id;
        });
    }

    static CompletableFuture<Integer> fetchUserScore(String name) {
        return CompletableFuture.supplyAsync(() -> {
            sleep(300);
            return name.length() * 10;
        });
    }

    static void sleep(int ms) {
        try { Thread.sleep(ms); } catch (InterruptedException e) {}
    }

    public static void main(String[] args) throws Exception {
        CompletableFuture<String> pipeline = fetchUserName(42)
            .thenCompose(CompletableFutureExample::fetchUserScore)
            .thenApply(score -> "Score: " + score)
            .exceptionally(ex -> "Error: " + ex.getMessage());

        System.out.println(pipeline.get());

        CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> "Hello");
        CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> "World");

        String combined = f1.thenCombine(f2, (a, b) -> a + " " + b).get();
        System.out.println("Combined: " + combined);

        List<CompletableFuture<String>> futures = List.of(
            CompletableFuture.supplyAsync(() -> "Task1"),
            CompletableFuture.supplyAsync(() -> "Task2"),
            CompletableFuture.supplyAsync(() -> "Task3")
        );

        CompletableFuture<Void> all = CompletableFuture.allOf(
            futures.toArray(new CompletableFuture[0])
        );
        all.thenRun(() -> System.out.println("All tasks done")).get();
    }
}