Here you can find the source of failAfter(Duration duration)
Parameter | Description |
---|---|
duration | The duration to timeout after. |
T | Ignored, since the future will always timeout. |
public static <T> CompletableFuture<T> failAfter(Duration duration)
//package com.java2s; //License from project: Apache License import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Main { private static final ScheduledExecutorService scheduler = Executors .newScheduledThreadPool(1, new ThreadFactoryBuilder() .setDaemon(true).setNameFormat("failAfter-%d").build()); /**/*from www . java2 s .co m*/ * Generates a completable future which times out. * inspired by NoBlogDefFound: http://www.nurkiewicz.com/2014/12/asynchronous-timeouts-with.html * * @param duration The duration to timeout after. * @param <T> Ignored, since the future will always timeout. * @return A completable future that will time out. */ public static <T> CompletableFuture<T> failAfter(Duration duration) { final CompletableFuture<T> promise = new CompletableFuture<>(); scheduler.schedule(() -> { final TimeoutException ex = new TimeoutException("Timeout after " + duration.toMillis() + " ms"); return promise.completeExceptionally(ex); }, duration.toMillis(), TimeUnit.MILLISECONDS); return promise; } }