-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
CompletableFutures.java
49 lines (38 loc) · 1.7 KB
/
CompletableFutures.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.pivovarit.allof;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
public final class CompletableFutures {
private CompletableFutures() {
}
public static <T> CompletableFuture<T> either(CompletableFuture<T> f1, CompletableFuture<T> f2) {
CompletableFuture<T> result = new CompletableFuture<>();
CompletableFuture.allOf(f1, f2).whenComplete((__, throwable) -> {
if (f1.isCompletedExceptionally() && f2.isCompletedExceptionally()) {
result.completeExceptionally(throwable);
}
});
f1.thenAccept(result::complete);
f2.thenAccept(result::complete);
return result;
}
public static <T> CompletableFuture<List<T>> allOf(Collection<CompletableFuture<T>> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(__ -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
}
public static <T> CompletableFuture<List<T>> allOfOrException(Collection<CompletableFuture<T>> futures) {
CompletableFuture<List<T>> result = allOf(futures);
for (CompletableFuture<?> f : futures) {
f.handle((__, ex) -> ex == null || result.completeExceptionally(ex));
}
return result;
}
public static <T> CompletableFuture<T> anyOf(List<CompletableFuture<T>> cfs) {
return CompletableFuture.anyOf(cfs.toArray(new CompletableFuture[0])).thenApply(o -> (T) o);
}
}