-
Notifications
You must be signed in to change notification settings - Fork 612
/
CompletableFutures.java
61 lines (52 loc) · 2.17 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
50
51
52
53
54
55
56
57
58
59
60
61
package org.infinispan.util.concurrent;
import org.infinispan.commons.util.InfinispanCollections;
import org.infinispan.commons.util.concurrent.NotifyingNotifiableFuture;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static java.util.Objects.requireNonNull;
import java.util.Map;
/**
* Utility methods connecting {@link CompletableFuture} futures and our {@link NotifyingNotifiableFuture} futures.
*
* @author Dan Berindei
* @since 8.0
*/
public class CompletableFutures {
private static final CompletableFuture completedEmptyMapFuture = CompletableFuture.completedFuture(InfinispanCollections.emptyMap());
public static <K,V> CompletableFuture<Map<K, V>> returnEmptyMap() {
return (CompletableFuture<Map<K, V>>) completedEmptyMapFuture;
}
public static <T> void connect(NotifyingNotifiableFuture<T> sink, CompletableFuture<T> source) {
CompletableFuture<T> compoundSource = source.whenComplete((value, throwable) -> {
if (throwable == null) {
sink.notifyDone(value);
} else {
sink.notifyException(throwable);
}
});
sink.setFuture(compoundSource);
}
/**
* It waits until the {@link CompletableFuture} is completed.
* <p>
* It ignore if the {@link CompletableFuture} is completed normally or exceptionally.
*
* @param future the {@link CompletableFuture} to test.
* @param time the timeout.
* @param unit the timeout unit.
* @return {@code true} if completed, {@code false} if timed out.
* @throws InterruptedException if interrupted while waiting.
* @throws NullPointerException if {@code future} or {@code unit} is {@code null}.
*/
public static boolean await(CompletableFuture<?> future, long time, TimeUnit unit) throws InterruptedException {
try {
requireNonNull(future, "Completable Future must be non-null.").get(time, requireNonNull(unit, "Time Unit must be non-null"));
return true;
} catch (ExecutionException e) {
return true;
} catch (java.util.concurrent.TimeoutException e) {
return false;
}
}
}