Skip to content

Instantly share code, notes, and snippets.

@viveknaskar
Last active September 22, 2022 21:37
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/2dfd26f9e4deb3aaa59eacc635ec5ebb to your computer and use it in GitHub Desktop.
Save viveknaskar/2dfd26f9e4deb3aaa59eacc635ec5ebb to your computer and use it in GitHub Desktop.
Illustration of thenCombine method of CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class ThenCombineExample {
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";
}).thenCombine(CompletableFuture.supplyAsync(() -> " World!"), //combining the two CompletableFuture results
(msg1, msg2) -> msg1 + msg2); // thenCombine() accepts a future and fn with two args to execute the task
// 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