Created
August 25, 2020 13:46
-
-
Save tivrfoa/9ede1f88fd64b0160d85a2e29bb1b947 to your computer and use it in GitHub Desktop.
Java Async with callback
This file contains hidden or 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.*; | |
| /** | |
| * A good tutorial can be found here: | |
| * @see <a href="https://www.baeldung.com/java-completablefuture"> | |
| * https://www.baeldung.com/java-completablefuture</a> | |
| */ | |
| class Async1 { | |
| static String f1(String result) { | |
| System.out.println("I'm f1"); | |
| // for (int i = 1; i < 4; ++i) | |
| // System.out.printf("Can you see me? %d\n", i); | |
| System.out.println(result); | |
| return result; | |
| } | |
| public static void main(String[] args) throws Exception { | |
| CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> { | |
| try {Thread.sleep(3000);}catch(Exception e) {} | |
| return "Maybe this won't be printed!!"; | |
| }); | |
| CompletableFuture<String> result = cf.thenApply(Async1::f1); // f1 is the callback =) | |
| System.out.println("result = " + result); | |
| System.out.println("Code continues ..."); | |
| System.out.println("Let's wait calling the get() method"); | |
| cf.get(); // waits to complete, but doesn't mean f1 will finish | |
| System.out.println("result = " + result); | |
| System.out.println("THE END"); | |
| System.out.println("result = " + result); | |
| } | |
| } | |
| /* | |
| These are one of the possible results: | |
| $ java Async1 | |
| result = java.util.concurrent.CompletableFuture@46f5f779[Not completed] | |
| Code continues ... | |
| Let's wait calling the get() method | |
| I'm f1 | |
| Maybe this won't be printed!! | |
| result = java.util.concurrent.CompletableFuture@46f5f779[Not completed] | |
| THE END | |
| result = java.util.concurrent.CompletableFuture@46f5f779[Completed normally] | |
| $ java Async1 | |
| result = java.util.concurrent.CompletableFuture@6842775d[Not completed] | |
| Code continues ... | |
| Let's wait calling the get() method | |
| result = java.util.concurrent.CompletableFuture@6842775d[Not completed] | |
| THE END | |
| I'm f1 | |
| Maybe this won't be printed!! | |
| result = java.util.concurrent.CompletableFuture@6842775d[Not completed] | |
| $ java Async1 | |
| result = java.util.concurrent.CompletableFuture@6842775d[Not completed] | |
| Code continues ... | |
| Let's wait calling the get() method | |
| result = java.util.concurrent.CompletableFuture@6842775d[Not completed] | |
| THE END | |
| result = java.util.concurrent.CompletableFuture@6842775d[Not completed] | |
| I'm f1 | |
| Maybe this won't be printed!! | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment