> For the complete documentation index, see [llms.txt](https://amartyushov.gitbook.io/tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://amartyushov.gitbook.io/tech/programming-languages/java/multithreading/future-completablefuture.md).

# Future, CompletableFuture

<figure><img src="/files/axOMgOE4khN3eNF6QPMS" alt=""><figcaption></figcaption></figure>

Below described a problem, when several Futures are submitted and you try to wait for them using `.get()` in a loop. There is no guarantee which will be the order of all these Futures execution. So your main thread will wait until your first Future in a loop will return anything:

<figure><img src="/files/cJLpVhj4ocIU20awowPA" alt=""><figcaption></figcaption></figure>

## Completable future

```java
Supplier<String> supplier = () -> "Hello";
CompletableFuture<String> future = CompletableFuture.supplyAsync(supplier);
future.join(); // this is a blocking code
```

### ofAll

{% code fullWidth="true" %}

```java
CompletableFuture<Weather> future1 = CompletableFuture.supplyAsync(new WeatherRetriever()::getWeather);
CompletableFuture<Weather> future2 = CompletableFuture.supplyAsync(new WeatherRetriever()::getWeather);
CompletableFuture<Weather> future3 = CompletableFuture.supplyAsync(new WeatherRetriever()::getWeather);

CompletableFuture<Void> done = CompletableFuture.allOf(future1, future2, future3);
done.thenApply( v -> Stream.of(future1, future2, future3)
// this is kind of blocking, but at this moment all futures are completed
    .map(CompletableFuture::join)
).join();

```

{% endcode %}

### Composing results of futures

{% code fullWidth="true" %}

```java
CompletableFuture<TheJump> jumpFuture = CompletableFuture.supplyAsync(Jumper::jump);
CompletableFuture<TheSwim> swimFuture = CompletableFuture.supplyAsync(Swimmer::swim);

SportResult result = jumpFuture.thenCompose(
		jumpResult -> swimFuture.thenApply(
				swimResult -> new SportResult(jumpResult, swimResult)
		)
).join();
```

{% endcode %}

<figure><img src="/files/hf3tkYVFxalPW5aopVUZ" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/Ov0DcbjgzcRePhp4SmXN" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/AaOd3fdT7TBSgRDpil2i" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/TyNHL5DIYEppOy1ANfeO" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/N5V6AGU3NxIAFyaIzPaO" alt=""><figcaption></figcaption></figure>
