Skip to content

Instantly share code, notes, and snippets.

@viveknaskar
Created September 20, 2022 22:28
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/7f6d8213010f05f2d34300c1db00f807 to your computer and use it in GitHub Desktop.
Save viveknaskar/7f6d8213010f05f2d34300c1db00f807 to your computer and use it in GitHub Desktop.
Illustration of thenRun method of CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class ThenRunExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
// delaying the thread by 2 seconds
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Hello!";
}).thenRun(() -> System.out.println("Completed after 2 seconds."));
// get() blocks and gets the result of the Future
completableFuture.get();
}
}
// Output: Completed after 2 seconds.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment