-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Async.java
217 lines (184 loc) · 7.3 KB
/
Async.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package graphql.execution;
import graphql.Assert;
import graphql.Internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.function.Supplier;
@Internal
@SuppressWarnings("FutureReturnValueIgnored")
public class Async {
public interface CombinedBuilder<T> {
void add(CompletableFuture<T> completableFuture);
CompletableFuture<List<T>> await();
}
/**
* Combines 0 or more CF into one. It is a wrapper around <code>CompletableFuture.allOf</code>.
*
* @param expectedSize how many we expect
* @param <T> for two
*
* @return a combined builder of CFs
*/
public static <T> CombinedBuilder<T> ofExpectedSize(int expectedSize) {
if (expectedSize == 0) {
return new Empty<>();
} else if (expectedSize == 1) {
return new Single<>();
} else {
return new Many<>(expectedSize);
}
}
private static class Empty<T> implements CombinedBuilder<T> {
private int ix;
@Override
public void add(CompletableFuture<T> completableFuture) {
this.ix++;
}
@Override
public CompletableFuture<List<T>> await() {
Assert.assertTrue(ix == 0, () -> "expected size was " + 0 + " got " + ix);
return CompletableFuture.completedFuture(Collections.emptyList());
}
}
private static class Single<T> implements CombinedBuilder<T> {
// avoiding array allocation as there is only 1 CF
private CompletableFuture<T> completableFuture;
private int ix;
@Override
public void add(CompletableFuture<T> completableFuture) {
this.completableFuture = completableFuture;
this.ix++;
}
@Override
public CompletableFuture<List<T>> await() {
Assert.assertTrue(ix == 1, () -> "expected size was " + 1 + " got " + ix);
CompletableFuture<List<T>> overallResult = new CompletableFuture<>();
completableFuture
.whenComplete((ignored, exception) -> {
if (exception != null) {
overallResult.completeExceptionally(exception);
return;
}
List<T> results = Collections.singletonList(completableFuture.join());
overallResult.complete(results);
});
return overallResult;
}
}
private static class Many<T> implements CombinedBuilder<T> {
private final CompletableFuture<T>[] array;
private int ix;
@SuppressWarnings("unchecked")
private Many(int size) {
this.array = new CompletableFuture[size];
this.ix = 0;
}
@Override
public void add(CompletableFuture<T> completableFuture) {
array[ix++] = completableFuture;
}
@Override
public CompletableFuture<List<T>> await() {
Assert.assertTrue(ix == array.length, () -> "expected size was " + array.length + " got " + ix);
CompletableFuture<List<T>> overallResult = new CompletableFuture<>();
CompletableFuture.allOf(array)
.whenComplete((ignored, exception) -> {
if (exception != null) {
overallResult.completeExceptionally(exception);
return;
}
List<T> results = new ArrayList<>(array.length);
for (CompletableFuture<T> future : array) {
results.add(future.join());
}
overallResult.complete(results);
});
return overallResult;
}
}
@FunctionalInterface
public interface CFFactory<T, U> {
CompletableFuture<U> apply(T input, int index, List<U> previousResults);
}
public static <T, U> CompletableFuture<List<U>> each(Collection<T> list, BiFunction<T, Integer, CompletableFuture<U>> cfFactory) {
CombinedBuilder<U> futures = ofExpectedSize(list.size());
int index = 0;
for (T t : list) {
CompletableFuture<U> cf;
try {
cf = cfFactory.apply(t, index++);
Assert.assertNotNull(cf, () -> "cfFactory must return a non null value");
} catch (Exception e) {
cf = new CompletableFuture<>();
// Async.each makes sure that it is not a CompletionException inside a CompletionException
cf.completeExceptionally(new CompletionException(e));
}
futures.add(cf);
}
return futures.await();
}
public static <T, U> CompletableFuture<List<U>> eachSequentially(Iterable<T> list, CFFactory<T, U> cfFactory) {
CompletableFuture<List<U>> result = new CompletableFuture<>();
eachSequentiallyImpl(list.iterator(), cfFactory, 0, new ArrayList<>(), result);
return result;
}
private static <T, U> void eachSequentiallyImpl(Iterator<T> iterator, CFFactory<T, U> cfFactory, int index, List<U> tmpResult, CompletableFuture<List<U>> overallResult) {
if (!iterator.hasNext()) {
overallResult.complete(tmpResult);
return;
}
CompletableFuture<U> cf;
try {
cf = cfFactory.apply(iterator.next(), index, tmpResult);
Assert.assertNotNull(cf, () -> "cfFactory must return a non null value");
} catch (Exception e) {
cf = new CompletableFuture<>();
cf.completeExceptionally(new CompletionException(e));
}
cf.whenComplete((cfResult, exception) -> {
if (exception != null) {
overallResult.completeExceptionally(exception);
return;
}
tmpResult.add(cfResult);
eachSequentiallyImpl(iterator, cfFactory, index + 1, tmpResult, overallResult);
});
}
/**
* Turns an object T into a CompletableFuture if it's not already
*
* @param t - the object to check
* @param <T> for two
*
* @return a CompletableFuture
*/
public static <T> CompletableFuture<T> toCompletableFuture(T t) {
if (t instanceof CompletionStage) {
//noinspection unchecked
return ((CompletionStage<T>) t).toCompletableFuture();
} else {
return CompletableFuture.completedFuture(t);
}
}
public static <T> CompletableFuture<T> tryCatch(Supplier<CompletableFuture<T>> supplier) {
try {
return supplier.get();
} catch (Exception e) {
CompletableFuture<T> result = new CompletableFuture<>();
result.completeExceptionally(e);
return result;
}
}
public static <T> CompletableFuture<T> exceptionallyCompletedFuture(Throwable exception) {
CompletableFuture<T> result = new CompletableFuture<>();
result.completeExceptionally(exception);
return result;
}
}