Skip to content

Commit aee7923

Browse files
committed
perf: optimize memory usage in mostSuccessOf* methods by not retaining unneeded exception instances 📝
1 parent f65b733 commit aee7923

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

cffu-core/src/main/java/io/foldright/cffu/CompletableFutureUtils.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -718,8 +718,10 @@ private static <T> CompletableFuture<T> f_mostSuccessTupleWithEhOf0(
718718
private static <T> CompletableFuture<T> f_mostSuccessTupleOf0(
719719
Executor executorWhenTimeout, long timeout, TimeUnit unit, CompletionStage<?>[] stages) {
720720
// 1. MUST be non-minimal-stage CF instances in order to read results(`getSuccessNow`), otherwise UnsupportedOpException.
721-
// 2. SHOULD copy input cfs to avoid memory leaks, otherwise all input cfs would be retained until output cf completes.
722-
final CompletableFuture<Object>[] cfArray = toNonMinCfCopyArray0(stages);
721+
// 2. SHOULD copy input cfs(by calling `exceptionally` method) to avoid memory leaks,
722+
// otherwise all input cfs would be retained until output cf completes.
723+
CompletableFuture<?>[] cfArray = mapArray(stages, CompletableFuture[]::new,
724+
s -> toNonMinCf0(s).exceptionally(v -> null));
723725
return cffuCompleteOnTimeout(CompletableFuture.allOf(cfArray), null, timeout, unit, executorWhenTimeout)
724726
.handle((unused, ex) -> f_tupleOf0(f_mGetSuccessNow0(null, cfArray)));
725727
}
@@ -945,8 +947,10 @@ private static <T> CompletableFuture<List<T>> mostSuccessResultsOf0(
945947
}
946948

947949
// 1. MUST be non-minimal-stage CF instances in order to read results(`getSuccessNow`), otherwise UnsupportedOpException.
948-
// 2. SHOULD copy input cfs to avoid memory leaks, otherwise all input cfs would be retained until output cf completes.
949-
final CompletableFuture<T>[] cfArray = toNonMinCfCopyArray0(cfs);
950+
// 2. SHOULD copy input cfs(by calling `exceptionally` method) to avoid memory leaks,
951+
// otherwise all input cfs would be retained until output cf completes.
952+
CompletableFuture<T>[] cfArray = mapArray(cfs, CompletableFuture[]::new,
953+
s -> LLCF.<T>toNonMinCf0(s).exceptionally(v -> valueIfNotSuccess));
950954
return cffuCompleteOnTimeout(CompletableFuture.allOf(cfArray), null, timeout, unit, executorWhenTimeout)
951955
.handle((unused, ex) -> arrayList(f_mGetSuccessNow0(valueIfNotSuccess, cfArray)));
952956
}

0 commit comments

Comments
 (0)