public class CompletableFutureTimeout
extends Object
java8中CompletableFuture异步处理超时的方法
Java 8 的 CompletableFuture 并没有 timeout 机制,虽然可以在 get 的时候指定 timeout,是一个同步堵塞的操作。怎样让
timeout 也是异步的呢?Java 8 内有内建的机 制支持,一般的实现方案是启动一个 ScheduledThreadpoolExecutor 线程在 timeout
时间后直接调用 CompletableFuture.completeExceptionally(new TimeoutException()),
然后用acceptEither() 或者 applyToEither 看是先计算完成还是先超时:
在 java 9 引入了 orTimeout 和 completeOnTimeOut 两个方法支持 异步 timeout 机制:
public CompletableFuture orTimeout(long timeout, TimeUnit unit) : completes the
CompletableFuture with a TimeoutException after the specified timeout has elapsed.
public CompletableFuture completeOnTimeout(T value, long timeout, TimeUnit unit) :
provides a default value in the case that the CompletableFuture pipeline times out.
内部实现上跟我们上面的实现方案是一模一样的,只是现在不需要自己实现了。
实际上hystrix等熔断的框架,其实现线程Timeout之后就关闭线程,也是基于同样的道理,所以我们可以看到hystrix中会有一个Timer Thread
- 从以下版本开始:
- 2.6.4
- 作者:
- luliang