Created
October 22, 2015 18:14
-
-
Save mcalavera81/59121bc6d9c08ea1d7ce to your computer and use it in GitHub Desktop.
CompletableFuture with Timeouts
This file contains 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
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; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think you should mention the source code uses snippets from: https://www.nurkiewicz.com/2014/12/asynchronous-timeouts-with.html