Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you complete a CompletableFuture when another set of CompletableFutures is complete?

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?

like image 744
poiuytrez Avatar asked Feb 08 '23 07:02

poiuytrez


2 Answers

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

like image 76
Vladimir Korenev Avatar answered Feb 13 '23 23:02

Vladimir Korenev


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();
}
like image 24
Sotirios Delimanolis Avatar answered Feb 13 '23 22:02

Sotirios Delimanolis