繁体   English   中英

CompletableFuture 中的异常传播 (java)

[英]Exception propagation in CompletableFuture (java)

如何将CompletableFuture.runAsync中的以下代码中遇到的异常传播到我的主线程? 我想在我的主线程中捕获IllegalStateException

CompletableFuture.runAsync(() -> {
        // some business logic which needs to run indefinitely
}).exceptionally(ex -> {
    // ex.printStackTrace();
    throw new IllegalStateException("Failed to process", ex);
});

一种选择是创建Throwable对象的Collection ,当CompletableFuture完成时,您可以将异常添加到集合中(如果它不为空)。 然后在您的主线程上,您可以轮询该集合。

        Set<Throwable> exception = new CopyOnWriteArraySet<>();

        CompletableFuture.runAsync(() -> {

        }).whenComplete((method, e) -> exception.add(e));

另一种选择是将whenCompleteExecutorService一起使用。 如果您不使用 ExecutorService,这可能不起作用。 这个想法是whenComplete将在mainThread ExecutorService 上返回。

        ExecutorService mainThread = Executors.newSingleThreadExecutor();
        
        CompletableFuture.runAsync(() -> {

        }).whenCompleteAsync((method, throwable) -> {
            // throw or handle in some way on main thread
        }, mainThread);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM