Last active
September 20, 2022 22:23
-
-
Save viveknaskar/fed44018468d84e4b687afac634244f7 to your computer and use it in GitHub Desktop.
Illustration of thenAccept method chaining for CompletableFuture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.TimeUnit; | |
public class ThenAcceptExample { | |
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!"; | |
}).thenAccept(msg -> | |
System.out.println("Message is " + msg)); //prints the result of the Future | |
// get() blocks and gets the result of the Future | |
completableFuture.get(); | |
} | |
} | |
// Output: Message is Hello! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment