2021年1月6日星期三

Why does this CompletableFuture work even when I don't call get() or join()?

I had a question while studying CompletableFuture. The get()/join() methods are blocking calls. What if I don't call either of them?

This code calls get():

// Case 1 - Use get()  CompletableFuture.runAsync(() -> {      try {          Thread.sleep(1_000L);      } catch (InterruptedException e) {          e.printStackTrace();      }      System.out.println("Hello");  }).get();  System.out.println("World!");    Thread.sleep(5_000L); // Don't finish the main thread  

Output:

Hello  World!  

This code calls neither get() nor join():

// Case 2 - Don't use get()  CompletableFuture.runAsync(() -> {      try {          Thread.sleep(1_000L);      } catch (InterruptedException e) {          e.printStackTrace();      }      System.out.println("Hello");  });  System.out.println("World!");    Thread.sleep(5_000L); // For don't finish main thread  

Output:

World!  Hello  

I don't know why the runnable block of case 2 is working.

https://stackoverflow.com/questions/65605550/why-does-this-completablefuture-work-even-when-i-dont-call-get-or-join January 07, 2021 at 09:40AM

没有评论:

发表评论