-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFutures.java
More file actions
62 lines (56 loc) · 2.28 KB
/
Futures.java
File metadata and controls
62 lines (56 loc) · 2.28 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
58
59
60
61
62
package net.theevilreaper.aves.util;
import org.jetbrains.annotations.NotNull;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
* Taken from <a href="https://github.com/Minestom/Arena/blob/master/src/main/java/net/minestom/arena/utils/ConcurrentUtils.java">...</a>
*
* @author theEvilReaper
* @version 1.0.0
* @since 1.0.0
**/
public final class Futures {
private Futures() {
}
/**
* Used to add timeout for CompletableFutures
*
* @param future the future which has to complete
* @param timeout duration to wait for the future to complete
* @param action Action to run after the future completes or the timeout is reached.<br>
* Parameter means:
* <ul>
* <li><b>true</b> - the timeout is reached</li>
* <li><b>false</b> - future completed before timeout</li>
* </ul>
* @return the new CompletionStage
*/
public static CompletableFuture<Void> thenRunOrTimeout(@NotNull CompletableFuture<?> future, @NotNull Duration timeout, Consumer<Boolean> action) {
final CompletableFuture<Boolean> f = new CompletableFuture<>();
CompletableFuture.delayedExecutor(timeout.toNanos(), TimeUnit.NANOSECONDS).execute(() -> f.complete(true));
future.thenRun(() -> f.complete(false));
return f.thenAccept(action);
}
/**
* Create a future from a CountDownLatch
*
* @param countDownLatch the countdown latch to wait for
* @return a future that completes when the countdown reaches zero
*/
public static @NotNull CompletableFuture<Void> futureFromCountdown(@NotNull CountDownLatch countDownLatch) {
final CompletableFuture<Void> future = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
try {
countDownLatch.await();
future.complete(null);
} catch (InterruptedException exception) {
future.completeExceptionally(new InterruptedException(exception.getMessage()));
Thread.currentThread().interrupt();
}
});
return future;
}
}