-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathCompletableFutureKit.java
More file actions
57 lines (48 loc) · 1.73 KB
/
CompletableFutureKit.java
File metadata and controls
57 lines (48 loc) · 1.73 KB
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
50
51
52
53
54
55
56
57
package org.dataloader.impl;
import org.dataloader.annotations.Internal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static java.util.stream.Collectors.toList;
/**
* Some really basic helpers when working with CompletableFutures
*/
@Internal
public class CompletableFutureKit {
public static <V> CompletableFuture<V> failedFuture(Exception e) {
CompletableFuture<V> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
public static <V> Throwable cause(CompletableFuture<V> completableFuture) {
if (!completableFuture.isCompletedExceptionally()) {
return null;
}
try {
completableFuture.get();
return null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return e;
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause != null) {
return cause;
}
return e;
}
}
public static <V> boolean succeeded(CompletableFuture<V> future) {
return future.isDone() && !future.isCompletedExceptionally();
}
public static <V> boolean failed(CompletableFuture<V> future) {
return future.isDone() && future.isCompletedExceptionally();
}
public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> cfs) {
return CompletableFuture.allOf(cfs.toArray(new CompletableFuture[0]))
.thenApply(v -> cfs.stream()
.map(CompletableFuture::join)
.collect(toList())
);
}
}