-
Notifications
You must be signed in to change notification settings - Fork 20
/
CombinedFuture.java
105 lines (93 loc) · 3 KB
/
CombinedFuture.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
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - info@scireum.de
*/
package sirius.kernel.async;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Permits to await the completion of multiple {@link Promise promises} or {@link Future futures}.
* <p>
* A CombinedFuture shall only be used once and after a call to <tt>asFuture</tt>, no further promises should be added.
* <p>
* The general call pattern looks like that:
* <pre>
* {@code
* CombinedFuture b = new CombinedFuture();
* b.add(somePromise);
* b.add(anotherPromise);
*
* b.asFuture().await(Duration.ofMinutes(1));
* }
* </pre>
*/
@ParametersAreNonnullByDefault
public class CombinedFuture {
private final AtomicInteger promisesOpen = new AtomicInteger(0);
private Throwable lastError;
private Future completionFuture;
/**
* Adds a promise to wait for.
* <p>
* Note that one must not call <tt>add</tt> after calling <tt>await</tt>.
*
* @param promise the promise to wait for
*/
@SuppressWarnings("unchecked")
public void add(Promise<?> promise) {
if (completionFuture != null) {
throw new IllegalStateException(
"Cannot add more promises to a CombinedFuture after await or asFuture has been called!");
}
promisesOpen.incrementAndGet();
((Promise<Object>) promise).onComplete(new CompletionHandler<Object>() {
@Override
public void onSuccess(@Nullable Object value) throws Exception {
handleSuccessfulPromise();
}
@Override
public void onFailure(Throwable throwable) throws Exception {
handleFailedPromise(throwable);
}
});
}
private void handleSuccessfulPromise() {
if (promisesOpen.decrementAndGet() > 0) {
return;
}
if (completionFuture == null) {
return;
}
if (lastError != null) {
completionFuture.fail(lastError);
} else {
completionFuture.success();
}
}
private void handleFailedPromise(Throwable throwable) {
lastError = throwable;
handleSuccessfulPromise();
}
/**
* Generates a new {@link Future} which completes if the last added promise completes or if any one of those fails.
*
* @return a new future which can be used to add completion handlers for all added promises.
*/
public Future asFuture() {
if (completionFuture == null) {
completionFuture = new Future();
if (promisesOpen.get() == 0) {
if (lastError != null) {
completionFuture.fail(lastError);
} else {
completionFuture.success();
}
}
}
return completionFuture;
}
}