Skip to content

Instantly share code, notes, and snippets.

@viveknaskar
Last active September 22, 2022 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viveknaskar/056d7a5fea854819f00dd08b39022431 to your computer and use it in GitHub Desktop.
Save viveknaskar/056d7a5fea854819f00dd08b39022431 to your computer and use it in GitHub Desktop.
Illustration of thenCompose method of CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class ThenComposeExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try { // delaying the thread by 2 seconds
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Hello";
}).thenCompose(msg -> CompletableFuture.supplyAsync(() ->
msg + " World!")); // thenCompose() receives a fn to return the result of the same type
// get() blocks and gets the result of the Future
System.out.println(completableFuture.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment