Reputation:
I'm looking to run two methods a()
and b()
that take in no arguments and return nothing (i.e. void methods) asynchronously such that they are returned in any order concurrently.
However, a third method c()
should only run after either of the other above methods complete.
I believe I am supposed to create two CompletableFuture objects (cf1 for a()
and cf2 b()
) and then use CompletableFuture.anyOf(cf1, cf2).join()
to block the code for c()
.
However, I am not sure how to create the cf1 and cf2 CompletableFuture objects. I understand the methods a()
and b()
are essentially like Runnable's run
method but I do not want to change the way they are implemented. Which of CompletableFuture's methods should I call in order to create this CompletableFuture objects for the two methods?
Thank you very much in advance for your help!
Upvotes: 6
Views: 19923
Reputation: 7828
Or you can directly use runAfterEither
as this
CompletableFuture<Void> a = CompletableFuture.runAsync(() -> {
Util.delay(new Random().nextInt(1000));
System.out.println("Hello ");
});
a = a.runAfterEither(CompletableFuture.runAsync(() -> {
Util.delay(new Random().nextInt(1000));
System.out.println("Hi ");
}), () -> {
System.out.println("world"); // your c();
});
a.join();
Upvotes: 2
Reputation: 3737
If I understand your question correctly, you can do something like this to wait until either of method a()
or b()
is completed and then once one of them is completed, you run method c()
.
CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> a());
CompletableFuture<Void> cf2 = CompletableFuture.runAsync(() -> b());
CompletableFuture<Void> cf3 = CompletableFuture.anyOf(cf1, cf2).thenRunAsync(() -> c());
Upvotes: 13