How do you populate a CompletableFuture when another set of CompletingFutures is completed?

I have a ready future (future1) that creates 10 terminating futures (futureN). Is there a way to set future1 as completed only when all futureN are completed?

+4
source share
2 answers

A CompletableFutureis not what acts, so I'm not sure what you mean by

which create 10 terminating futures

I assume that you set the task with runAsyncor submitAsync. My example will not be, but the behavior will be the same if you do.

root CompletableFuture. , ( Executor, runAsync Thread CompletableFuture ). 10 CompletableFuture CompletableFuture#allOf, CompletableFuture, , ( ), thenRun, .

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();
}
+2

, " ", , - , , : CompletableFuture.allOf(future2, future3, ..., futureN).thenRun(() -> future1.complete(value));

+6

Source: https://habr.com/ru/post/1619540/


All Articles