spotify / completable-futures

Utilities for working with futures in Java 8
Apache License 2.0
393 stars 51 forks source link

Add successfulAsList methods with partial failure actions #86

Closed mklamra closed 2 years ago

mklamra commented 2 years ago

This PR adds two successfulAsList methods:

successfulAsList with partial failure action Returns the results of the stages that succeed. If some but not all stages fail, the exceptions of the failed stages will be passed to the provided partial failure action without affecting the joined future. This is useful when you want to get all successful results without being affected if some of the stages fail.

Example:

List<CompletableFuture<String>> input = asList(
    completedFuture("a"),
    exceptionallyCompletedFuture(new RuntimeException("boom")));
CompletableFuture<List<String>> joined = CompletableFutures.successfulAsList(
    input,
    exceptions -> { System.err.println("Futures failed: " + exceptions); });

successfulAsList with partial failure action and predicate Returns the results of the stages that succeed and that satisfy a predicate. If some stages fail and some successful results satisfy the predicate, the exceptions of the failed stages will be passed to the provided partial failure action without affecting the joined future. This is useful when you want to get all successful results, but ignore some of them and without being affected if some of the stages fail.

Example:

List<CompletableFuture<String>> input = asList(
    completedFuture("a"),
    exceptionallyCompletedFuture(new RuntimeException("boom")));
CompletableFuture<List<String>> joined = CompletableFutures.successfulAsList(
    input,
    exceptions -> System.err.println("Futures failed: " + exceptions),
    value -> value.equals("a"));

One example use case is when retrieving multiple resources from an HTTP service. Assume that each resource is retrieved with a separate CompletionStage. When joining the stages, one might want to filter out missing resources, i.e. 404 responses, and make sure that they are ignored in the failure handling for the joined future. To achieve this, the 404 responses have to be filtered out before the stages are joined. That is implemented in this successfulAsList method.