Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CompletableFuture with Timeouts
package test;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Random;
import java.util.concurrent.*;
import java.util.function.Function;
public class CompletableFutureTest {
static public void main(String[] args) throws Exception {
Random random = new Random(Instant.now().getNano());
CompletableFuture<Integer> number =CompletableFuture.supplyAsync(() -> {
return task(random.nextInt(3000),2);
});
final CompletableFuture<Integer> responseFuture = within(number, Duration.ofSeconds(1));
CompletableFuture<Void> last = responseFuture
.thenAccept(System.out::print)
.exceptionally(throwable -> {
System.out.println("Unrecoverable error " + throwable);
return null;
});
last.thenRun(()-> System.exit(0));
}
public static <T> CompletableFuture<T> within(CompletableFuture<T> future, Duration duration) {
final CompletableFuture<T> timeout = failAfter(duration);
return future.applyToEither(timeout, Function.identity());
}
public static <T> CompletableFuture<T> failAfter(Duration duration) {
final CompletableFuture<T> promise = new CompletableFuture<>();
scheduler.schedule(() -> {
final TimeoutException ex = new TimeoutException("Timeout after " + duration);
return promise.completeExceptionally(ex);
}, duration.toMillis(), TimeUnit.MILLISECONDS);
return promise;
}
private static final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
static Integer task(long sleep, int number) {
try {
Thread.sleep(sleep);
System.out.println(Thread.currentThread().getName() + "with number " + number);
} catch (InterruptedException e) {
e.printStackTrace();
}
return number;
}
}
@shanerk

This comment has been minimized.

Copy link

@shanerk shanerk commented Mar 7, 2018

Thanks for this, it helped me out quite a bit.

@jelinski

This comment has been minimized.

Copy link

@jelinski jelinski commented Jan 23, 2020

I think you should mention the source code uses snippets from: https://www.nurkiewicz.com/2014/12/asynchronous-timeouts-with.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment