Java

CompletableFuture — Async Chains

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`CompletableFuture` is the idiomatic way to compose async work. `thenApply` for sync transforms, `thenCompose` for async chains (flatMap), `exceptionally` for fallback on failure.
Java
Raw
import java.util.concurrent.*;

class Demo {
    CompletableFuture<String> fetchUser(int id) {
        return CompletableFuture.supplyAsync(() -> {
            try { Thread.sleep(100); } catch (InterruptedException ignored) {}
            return "User " + id;
        });
    }

    CompletableFuture<Integer> countOrders(String user) {
        return CompletableFuture.supplyAsync(() -> user.length() * 2);
    }

    void example() throws Exception {
        // Chain — sync transform with thenApply, async chain with thenCompose
        var f = fetchUser(42)
            .thenApply(String::toUpperCase)
            .thenCompose(this::countOrders)        // chain another async call
            .thenApply(n -> "found " + n + " orders");

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

        // Fan-out + join
        var a = fetchUser(1);
        var b = fetchUser(2);
        var both = a.thenCombine(b, (x, y) -> x + " + " + y);
        System.out.println(both.get());

        // Error handling
        var safe = fetchUser(99)
            .thenApply(u -> { if (u.contains("99")) throw new RuntimeException("nope"); return u; })
            .exceptionally(ex -> "fallback: " + ex.getMessage());
        System.out.println(safe.get());
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.