Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

java - How to implement CompletableFuture.allOf() that completes exceptionally once any of the futures fail?

I want to implement a hybrid of CompletableFuture.allOf() and CompletableFuture.anyOf() where the returned future completes successfully as soon as all of the elements complete successfully, or it completes exceptionally (with the same exception) as soon as any of the elements complete exceptionally. In the case of multiple elements failing, returning the exception of any of them is sufficient.

Use-case

I have a task that needs to aggregate sub-results returned by a list of CompletableFutures, but that task should stop waiting as soon as any of them fails. I understand that the sub-tasks will keep on running and that's okay.

Related questions

I found Waiting on a list of Future which initially seems like a duplicate question but the accepted answer uses CompletionService which requires Callable or Runnable as input. I am looking for a solution that takes already-running CompletionStages as input.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This question is actually very similar to Replace Futures.successfulAsList with Java 8 CompletableFuture?

Although the question is not exactly the same, the same answer (from myself) should satisfy your needs.

You can implement this with a combination of allOf() and chaining each input future with an exceptionally() that would make the future returned by allOf() immediately fail:

CompletableFuture<String> a = …, b = …, c = …;
CompletableFuture<Void> allWithFailFast = CompletableFuture.allOf(a, b, c);
Stream.of(a, b, c)
    .forEach(f -> f.exceptionally(e -> {
        allWithFailFast.completeExceptionally(e);
        return null;
    }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...