HelloWhatsMyName1234
HelloWhatsMyName1234

Reputation: 105

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

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();

Upvotes: 2

Views: 742

Answers (2)

Eugene
Eugene

Reputation: 121048

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.

Upvotes: 1

Slava Vedenin
Slava Vedenin

Reputation: 60234

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);

Upvotes: 1

Related Questions