Created
May 24, 2018 01:23
-
-
Save mingliangguo/9fad301f3d605c264ee3aa671f48e50f to your computer and use it in GitHub Desktop.
[Java Async] sample async #java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://dzone.com/articles/asynchronous-timeouts | |
private static final ScheduledExecutorService scheduler = | |
Executors.newScheduledThreadPool( | |
1, | |
new ThreadFactoryBuilder() | |
.setDaemon(true) | |
.setNameFormat("failAfter-%d") | |
.build()); | |
public static <T> CompletableFuture<T> failAfter(Duration duration) { | |
final CompletableFuture<T> promise = new CompletableFuture<>(); | |
scheduler.schedule(() -> promise.completeExceptionally(new TimeoutException("Timeout after " + duration)), | |
duration.toMillis(), MILLISECONDS); | |
return promise; | |
} | |
public static <T> CompletableFuture<T> within(CompletableFuture<T> future, Duration duration) { | |
final CompletableFuture<T> timeout = failAfter(duration); | |
return future.applyToEither(timeout, Function.identity()); | |
} | |
// sample usage | |
final CompletableFuture<Response> responseFuture = within( | |
asyncCode(), Duration.ofSeconds(1)); | |
responseFuture | |
.thenAccept(this::send) | |
.exceptionally(throwable -> { | |
log.error("Unrecoverable error", throwable); | |
return null; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment