CompletableFuture 异步关于异常的坑

自定义线程池

@Configuration
public class ThreadPoolConfig {

    public static ThreadPoolExecutor getThreadPoolExecutor() {
        int availableProceSSOrs = Runtime.getRuntime().availableProcessors();
        return new ThreadPoolExecutor(
                availableProcessors,
                availableProcessors,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(9999),
                new ThreadFactoryBuilder().setNameFormat("custom-thread-pool-%d").build(),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

}

程序存在异常,却返回成功

写一个存在异常的程序,让其异步执行

public static final ThreadPoolExecutor CUSTOM_THREAD_POOL = ThreadPoolConfig.getThreadPoolExecutor();

/**
 * 异步执行异常测试
 */

@ApiOperation(value = "异步执行异常测试", code = 800)
@GetMapping("/asyncException")
public ResponseData<Object> asyncException() {
    try {
        try {
            CompletableFuture.runAsync(() -> {
                int i = 1 / 0;
            }, CUSTOM_THREAD_POOL);
        } catch (Exception e) {
            log.error("异常信息: " + e.getMessage(), e);
            throw new BusinessException(e.getMessage());
        }
        return new ResponseData<>(StatusCodeEnum.SUCCESS_CODE.getStatusCode(), "操作成功");
    } catch (Exception e) {
        return new ResponseData<>(StatusCodeEnum.ERROR_CODE.getStatusCode(), "操作失败:" + e.getMessage());
    }
}

结果:接口返回成功,控制台没有打印错误信息。

CompletableFuture 异步关于异常的坑

异步调用join()

// join方法获取异常信息: 将异步线程中发生的异常信息抛到主线程, 这样异常可被主线程捕获
try {
    CompletableFuture.runAsync(() -> {
        int i = 1 / 0;
    }, CUSTOM_THREAD_POOL).join();
catch (Exception e) {
    log.error("外层异常信息: " + e.getMessage(), e);
    throw new BusinessException(e.getMessage());
}

结果:接口返回失败,控制台打印异常日志

CompletableFuture 异步关于异常的坑

异步调用get()

异步方法中get()是阻塞的,在使用时要设置超时时间。

// get方法获取异常信息: 将异步线程中发生的异常信息抛到主线程, 这样异常可被主线程捕获
try {
    CompletableFuture.runAsync(() -> {
        int i = 1 / 0;
    }, CUSTOM_THREAD_POOL).get(2, TimeUnit.SECONDS);
catch (Exception e) {
    log.error("外层异常信息: " + e.getMessage(), e);
    throw new BusinessException(e.getMessage());
}

结果:接口返回成功,控制台打印异常信息。

CompletableFuture 异步关于异常的坑

异步调用exception()

// exceptionally获取异常信息: 异常是存在于异步当中的, 不能被主线程捕获
try {
    CompletableFuture.runAsync(() -> {
        int i = 1 / 0;
    }, CUSTOM_THREAD_POOL)
    .exceptionally(e -> {
        log.error("异步运行异常信息: " + e.getMessage(), e);
        throw new BusinessException(e.getMessage());
    });
catch (Exception e) {
    log.error("异常信息: " + e.getMessage(), e);
    throw new BusinessException(e.getMessage());
}

结果:接口返回成功,控制台打印异步线程异常日志,主线程没有打印异常日志

CompletableFuture 异步关于异常的坑

异步调用whenComplete()

// whenComplete获取异常信息: 异常是存在于异步当中的, 不能被主线程捕获
try {
    CompletableFuture.runAsync(() -> {
        int i = 1 / 0;
    }, CUSTOM_THREAD_POOL)
    .whenComplete((r, e) -> {
        if (e != null) {
            log.error("异步执行异常信息: " + e.getMessage(), e);
            throw new BusinessException(e.getMessage());
        }
    });
catch (Exception e) {
    log.error("异常信息: " + e.getMessage(), e);
    throw new BusinessException(e.getMessage());
}

结果:结果返回成功,控制台打印异步线程异常信息,主线程没有打印异常信息

CompletableFuture 异步关于异常的坑

异步调用handle()

// handle获取异常信息: 异常是存在于异步当中的, 不能被主线程捕获
try {
    CompletableFuture.runAsync(() -> {
        int i = 1 / 0;
    }, CUSTOM_THREAD_POOL)
    .handle((r, e) -> {
        if (e != null) {
            log.error("异步执行异常信息: " + e.getMessage(), e);
            throw new BusinessException(e.getMessage());
        }
        return null;
    });
catch (Exception e) {
    log.error("异常信息: " + e.getMessage(), e);
    throw new BusinessException(e.getMessage());
}

结果:结果返回成功,控制台打印异步线程异常信息,主线程没有打印异常信息

CompletableFuture 异步关于异常的坑

程序发生异常时需要做处理,可以调用get()/join()

try {
    CompletableFuture.runAsync(() -> {
        int i = 1 / 0;
    }, CUSTOM_THREAD_POOL)
    .exceptionally(e -> {
        log.error("异步执行异常信息: " + e.getMessage(), e);
        throw new BusinessException(e.getMessage());
    }).join();
catch (Exception e) {
    log.error("异常信息: " + e.getMessage(), e);
    throw new BusinessException(e.getMessage());
}

try {
    CompletableFuture.runAsync(() -> {
        int i = 1 / 0;
    }, CUSTOM_THREAD_POOL)
    .exceptionally(e -> {
        log.error("异步执行异常信息: " + e.getMessage(), e);
        throw new BusinessException(e.getMessage());
    }).get(2, TimeUnit.SECONDS);
catch (Exception e) {
    log.error("异常信息: " + e.getMessage(), e);
    throw new BusinessException(e.getMessage());
}
CompletableFuture 异步关于异常的坑

程序发生异常时不做处理直接报错,直接调用get()/join()

直接的异步方法后调用get()/join()。

总结

在使用异步CompletableFuture时,无论是否有返回值都要调用get()/join()方法,避免程序执行报错了,仍然返回成功。如果在程序报错时需要对上一个异步任务结果做其他操作,可以调用whenComplete()handle()处理,如果只是对异常做处理,不涉及对上一个异步任务结果的情况,调用exceptionally()处理。

来源:blog.csdn.net/weixin_43356538/

article/details/129705507

后端专属技术群

构建高质量的技术交流社群,欢迎从事编程开发、技术招聘HR进群,也欢迎大家分享自己公司的内推信息,相互帮助,一起进步!

文明发言,以交流技术职位内推行业探讨为主

广告人士勿入,切勿轻信私聊,防止被骗

CompletableFuture 异步关于异常的坑
加我好友,拉你进群

原文始发于微信公众号(Java知音):CompletableFuture 异步关于异常的坑

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/147604.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!