Skip to content

Instantly share code, notes, and snippets.

@mingliangguo
Created May 24, 2018 01:23
Show Gist options
  • Save mingliangguo/9fad301f3d605c264ee3aa671f48e50f to your computer and use it in GitHub Desktop.
Save mingliangguo/9fad301f3d605c264ee3aa671f48e50f to your computer and use it in GitHub Desktop.
[Java Async] sample async #java
// 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