异步多线程超时报错 CompletableFuture

首先定义一个定时池计算时间

package org.example;

/**
 * date: 2022-08-10
 *
 * @author xuhb
 **/


import java.util.concurrent.*;


public class CompletableFutureTimeout {
    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;
        }
    }


    public static <T> CompletableFuture<T> timeoutAfter(long timeOut, TimeUnit timeUnit, Exception e) {
        final CompletableFuture<T> promise = new CompletableFuture<>();
        SCHEDULER.schedule(() -> promise.completeExceptionally(e), timeOut, timeUnit);
        return promise;
    }


    private static final ScheduledExecutorService SCHEDULER =
            Executors.newScheduledThreadPool(1, new DaemonThreadFactory());

}

用法

CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },THREAD_POOL).whenComplete((unused, throwable) -> {
            if (throwable != null) {
                log.error(" 报错", throwable);
            }
        }).applyToEither(CompletableFutureTimeout.timeoutAfter(1L, TimeUnit.SECONDS, new RuntimeException("sssss")), Function.identity()).exceptionally(throwable -> { log.error(" 超时", throwable); return null; });

代码来源

CompletableFuture with Timeouts · GitHub

文章来源
Asynchronous timeouts with CompletableFuture (nurkiewicz.com)

推荐一个京东的异步并发框架  https://gitee.com/jd-platform-opensource/asyncTool

posted @ 2022-08-10 16:30  大哥超帅  阅读(542)  评论(0编辑  收藏  举报