poiuytrez
poiuytrez

Reputation: 22546

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?

Upvotes: 5

Views: 5425

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280172

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

Upvotes: 2

Vladimir Korenev
Vladimir Korenev

Reputation: 1166

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

Upvotes: 7

Related Questions