Future, CompletableFuture

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:

Completable future

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

ofAll

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();

Composing results of futures

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();

Last updated