// Created on savesnippets.com · https://savesnippets.com/luSmXCl8fVnCjl import java.util.concurrent.*; class Demo { CompletableFuture fetchUser(int id) { return CompletableFuture.supplyAsync(() -> { try { Thread.sleep(100); } catch (InterruptedException ignored) {} return "User " + id; }); } CompletableFuture 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()); } }