Skip to content

Instantly share code, notes, and snippets.

@mcalavera81
Created October 22, 2015 18:14
Show Gist options
  • Save mcalavera81/59121bc6d9c08ea1d7ce to your computer and use it in GitHub Desktop.
Save mcalavera81/59121bc6d9c08ea1d7ce to your computer and use it in GitHub Desktop.
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
Copy link

shanerk commented Mar 7, 2018

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

@jelinski
Copy link

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