java8中CompletableFuture异步处理超时的方法

stackoverflow上有一个讨论:Timeout with default value in Java 8 CompletableFuture

其中大家讨论了实现方案
其中的一个解决方案:
原文链接:Asynchronous Timeouts with CompletableFuture

如何实现Asynchronous timeouts

Java 8 的 CompletableFuture 并没有 timeout 机制,虽然可以在 get 的时候指定 timeout,但是我们知道get 是一个同步堵塞的操作。怎样让 timeout 也是异步的呢?

timeout异步就是说,如果forkjoin-pool中一个线程在规定时间内没有返回,那么就结束掉,而不是继续执行直到获取结果,比如main线程200ms内返回,但forkjoin-pool中某个执行线程执行400ms才返回,而其返回值根本没有被使用到

Java 8 内有内建的机制支持,一般的实现方案是启动一个 ScheduledThreadpoolExecutor 线程在 timeout 时间后直接调用 CompletableFuture.completeExceptionally(new TimeoutException()),然后用 acceptEither() 或者 applyToEither 看是先计算完成还是先超时:

public static <T> CompletableFuture<T> within(CompletableFuture<T> future, long timeout, TimeUnit unit) {
    final CompletableFuture<T> timeoutFuture = timeoutAfter(timeout, unit);
    // 哪个先完成 就apply哪一个结果 这是一个关键的API
    return future.applyToEither(timeoutFuture, Function.identity());
}

一个简单的 timeoutAfter 实现如下:

public static <T> CompletableFuture<T> timeoutAfter(long timeout, TimeUnit unit) {
    CompletableFuture<T> result = new CompletableFuture<T>();
    // timeout 时间后 抛出TimeoutException 类似于sentinel / watcher
    delayer.schedule(() -> result.completeExceptionally(new TimeoutException()), timeout, unit);
    return result;
}

其中 delayer 是 ScheduledThreadPoolExecutor 的一个实例:

    /**
     * Singleton delay scheduler, used only for starting and * cancelling tasks.
     */
    static final class Delayer {
        static ScheduledFuture<?> delay(Runnable command, long delay,
                                        TimeUnit unit) {
            return delayer.schedule(command, delay, unit);
        }

        static final class DaemonThreadFactory implements ThreadFactory {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                t.setName("CompletableFutureDelayScheduler");
                return t;
            }
        }

        static final ScheduledThreadPoolExecutor delayer;

        // 注意,这里使用一个线程就可以搞定 因为这个线程并不真的执行请求 而是仅仅抛出一个异常
        static {
            (delayer = new ScheduledThreadPoolExecutor(
                    1, new DaemonThreadFactory())).
                    setRemoveOnCancelPolicy(true);
        }
    }

示例demo参考:https://gitee.com/constfafa/spring_springboot_learning/tree/master/deferresult-demo
cn.bellychang.controller.AsyncController#orderCompletionStage

在 java 9 引入了 orTimeoutcompleteOnTimeOut 两个方法支持 异步 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
在这里插入图片描述

比如alibaba sentinel中也有一个Timer Thread
在这里插入图片描述

  • 9
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
CompletableFutureJava 8 引入的一个类,用于实现多线程的异步编程。它提供了丰富的方法处理异步任务的结果、组合多个异步任务以及处理异常情况。 要实现超时处理,你可以结合 CompletableFuture方法Java 的 ScheduledExecutorService 来实现。下面是一个示例: ```java import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class CompletableFutureTimeoutExample { public static void main(String[] args) { // 创建一个 ScheduledExecutorService 用于超时处理 ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); // 创建一个 CompletableFuture 对象 CompletableFuture<String> future = new CompletableFuture<>(); // 设置超时时间 long timeout = 5000; // 5秒 // 在指定时间后取消 CompletableFuture executorService.schedule(() -> { if (!future.isDone()) { future.completeExceptionally(new TimeoutException("Timeout")); } }, timeout, TimeUnit.MILLISECONDS); // 异步任务 CompletableFuture.runAsync(() -> { try { // 执行异步操作,例如网络请求、数据库查询等 String result = performAsyncTask(); // 当任务完成时,设置结果给 CompletableFuture future.complete(result); } catch (Exception e) { future.completeExceptionally(e); } }); // 获取结果或处理超时异常 try { String result = future.get(); // 处理成功结果 } catch (TimeoutException e) { // 处理超时异常 } catch (InterruptedException | ExecutionException e) { // 处理其他异常 } // 关闭 ScheduledExecutorService executorService.shutdown(); } private static String performAsyncTask() { // 执行异步任务的逻辑 return "Async task result"; } } ``` 在上面的示例,我们创建了一个 CompletableFuture 对象,并使用 ScheduledExecutorService 在指定的超时时间后取消 CompletableFuture。然后,我们使用 CompletableFuture.runAsync 方法执行异步任务,并在任务完成时设置结果给 CompletableFuture。最后,我们使用 future.get() 方法来获取结果或处理超时异常。 希望以上信息能够帮助到你!如果你还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值