# CompletableFuture — Advanced Java

Source: https://www.geekswithgeeks.com/en/advanced-java/adv-completablefuture

> Compose non-blocking asynchronous pipelines with thenApply, thenCompose and thenCombine, and recover from failures using exceptionally and handle.

## Chain, combine, handle

`thenApply` transforms a result, `thenCompose` flat-maps another async call, `thenCombine` joins two, `exceptionally` / `handle` recover from failure — all without blocking.

```java
CompletableFuture
    .supplyAsync(() -> fetchUser(id), pool)
    .thenCompose(u -> loadOrdersAsync(u))
    .thenApply(this::summarise)
    .exceptionally(ex -> Summary.empty())
    .thenAccept(System.out::println);
```

## Async variants and combining many

`thenApply` runs its continuation on whichever thread completed the future (could be the caller!); `thenApplyAsync(fn, pool)` guarantees it runs on your pool. `CompletableFuture.allOf(...)` waits for every future; `anyOf(...)` waits for the first to finish.
