Skip to content

Commit

Permalink
feat(imp):[#214] improved variable naming and code comment
Browse files Browse the repository at this point in the history
  • Loading branch information
dsmf committed Feb 2, 2024
1 parent e13eb7e commit 0cfba0f
Showing 1 changed file with 10 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,15 @@ public <T> CompletableFuture<T> getFastestResult(final List<CompletableFuture<T>

log.debug("Trying to get fastest result from list of futures");

final CompletableFuture<T> fastestResultPromise = new CompletableFuture<>();
// The purpose of this overall future is to track when the first data request is successful.
// This way we do not need to wait for the others to complete.
final CompletableFuture<T> overallFuture = new CompletableFuture<>();

final List<Throwable> exceptions = new ArrayList<>();

final var futuresList = futures.stream()
.map(future -> future.exceptionally(collectingExceptionsAndThrow(exceptions))
.handle(completingOnFirstSuccessful(fastestResultPromise)))
.handle(completingOnFirstSuccessful(overallFuture)))
.toList();

allOf(toArray(futuresList)).whenComplete((value, ex) -> {
Expand All @@ -81,37 +83,36 @@ public <T> CompletableFuture<T> getFastestResult(final List<CompletableFuture<T>
.map(ExceptionUtils::getStackTrace)
.collect(Collectors.joining(System.lineSeparator())), ex);

fastestResultPromise.completeExceptionally(new CompletionExceptions("None successful", exceptions));
overallFuture.completeExceptionally(new CompletionExceptions("None successful", exceptions));
} else {
log.debug("Completing");
fastestResultPromise.complete(null);
overallFuture.complete(null);
}
});

return fastestResultPromise;
return overallFuture;
}

private static <T> CompletableFuture<T>[] toArray(final List<CompletableFuture<T>> handledFutures) {
return handledFutures.toArray(new CompletableFuture[0]);
}

private static <T> BiFunction<T, Throwable, Boolean> completingOnFirstSuccessful(
final CompletableFuture<T> resultPromise) {
final CompletableFuture<T> overallFuture) {

return (value, throwable) -> {

log.debug("value: '{}', throwable: {}", value, throwable);

final boolean notFinishedByOtherFuture = !resultPromise.isDone();
final boolean notFinishedByOtherFuture = !overallFuture.isDone();
log.debug("notFinishedByOtherFuture {} ", notFinishedByOtherFuture);

final boolean currentFutureSuccessful = throwable == null && value != null;

if (notFinishedByOtherFuture && currentFutureSuccessful) {

// first future that completes successfully completes the overall future
log.debug("First future that completed successfully");
resultPromise.complete(value);
overallFuture.complete(value);
return true;

} else {
Expand Down

0 comments on commit 0cfba0f

Please sign in to comment.