CompletableFuture — asynchronous programming with composition, allowing chaining of async operations.
1// Basic async2CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {3 return fetchData();4});56// Chain operations7CompletableFuture<User> userFuture = CompletableFuture8 .supplyAsync(() -> getUserId())9 .thenApply(id -> fetchUser(id))10 .thenApply(user -> enrichUser(user))11 .exceptionally(ex -> defaultUser());1213// Combine multiple futures14CompletableFuture<String> nameFuture = fetchName();15CompletableFuture<Integer> ageFuture = fetchAge();16CompletableFuture<String> combined = nameFuture17 .thenCombine(ageFuture, (name, age) -> name + " is " + age);1819// All of20CompletableFuture.allOf(future1, future2, future3).join();
Key methods: