Java CompletableFuture: Trying to run two void methods as CompletableFuture and block until both complete

Viewed 166

I am trying to run two void method1 and method2 async and then block the code until both methods are done.

Does this achieve that?

      CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> method1());
      CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> method2());
      CompletableFuture.allOf(future1, future2).join();
2 Answers

I think code CompletableFuture.allOf(future1, future2).join(); should work fine. Could you try this, did you have any problems?

Or you can use something like:

  Arrays.asList(future1,future1).forEach(Future::get);

Why don't you use the dedicated method runAsync though?

   public static void main(String[] args) {
      CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> method1());
      CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> method2());

      CompletableFuture<Void> compound = CompletableFuture.allOf(future1, future2);
      compound.join();
      System.out.println("compound done");
}

And yes, your compound will be "joined" on the other thread (main in the example above), as such that compound done message will be printed only after both methods executed.

Related