I have a completable future (future1) which create 10 completable futures (futureN). Is there a way to set future1 as complete only when all futureN are completed?
I am not sure what you mean by "future creates other futures" but if you have many futures and you want to do something when they are completed you can do it this way:
CompletableFuture.allOf(future2, future3, ..., futureN).thenRun(() -> future1.complete(value));
A CompletableFuture
is not something that acts so I'm unsure what you mean by
which create 10 completable futures
I'm assuming you mean you submitted a task with runAsync
or submitAsync
. My example won't, but the behavior is the same if you do.
Create your root CompletableFuture
. Then run some code asynchronously that creates your futures (through an Executor
, runAsync
, inside a new Thread
, or inline with CompletableFuture
return values). Collect the 10 CompletableFuture
objects and use CompletableFuture#allOf
to get a CompletableFuture
that will complete when they are all complete (exceptionally or otherwise). You can then add a continuation to it with thenRun
to complete your root future.
For example
public static void main(String args[]) throws Exception {
CompletableFuture<String> root = new CompletableFuture<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
CompletableFuture<String> cf1 = CompletableFuture.completedFuture("first");
CompletableFuture<String> cf2 = CompletableFuture.completedFuture("second");
System.out.println("running");
CompletableFuture.allOf(cf1, cf2).thenRun(() -> root.complete("some value"));
});
// once the internal 10 have completed (successfully)
root.thenAccept(r -> {
System.out.println(r); // "some value"
});
Thread.sleep(100);
executor.shutdown();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With