Future, CompletableFuture
Last updated
Last updated
Supplier<String> supplier = () -> "Hello";
CompletableFuture<String> future = CompletableFuture.supplyAsync(supplier);
future.join(); // this is a blocking codeCompletableFuture<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();
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();