Exception propagation in CompletableFuture (java):CompletableFuture中的异常传播

huangapple go评论75阅读模式
英文:

Exception propagation in CompletableFuture (java)

问题

我要捕获在以下代码中遇到的异常,然后传播到我的主线程中,我想在主线程中捕获IllegalStateException异常。

CompletableFuture.runAsync(() -> {
    // 需要无限运行的一些业务逻辑
}).exceptionally(ex -> {
    // ex.printStackTrace();
    throw new IllegalStateException("处理失败", ex);
});
英文:

How can I propagate exception encountered in the following code inside CompletableFuture.runAsync to my main thread? I want to catch the IllegalStateException in my main thread.

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

答案1

得分: 1

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

另一种选择是使用 whenComplete 结合 ExecutorService。如果您没有使用 ExecutorService,这种方法可能不适用。思路是 whenComplete 会在主线程的 ExecutorService 上返回。

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

CompletableFuture.runAsync(() -> {

}).whenComplete((method, e) -> exception.add(e));
ExecutorService mainThread = Executors.newSingleThreadExecutor();

CompletableFuture.runAsync(() -> {

}).whenCompleteAsync((method, throwable) -> {
    // 在主线程上抛出异常或以某种方式处理
}, mainThread);
英文:

One option would be to create a Collection of Throwable objects and when the CompletableFuture completes you can add the exception to the Collection (if it's not null). Then on your main thread you could poll that Collection.

        Set&lt;Throwable&gt; exception = new CopyOnWriteArraySet&lt;&gt;();

        CompletableFuture.runAsync(() -&gt; {

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

Another option is to use whenComplete with ExecutorService. This may not work if you're not using an ExecutorService. The idea is that whenComplete will return on the mainThread ExecutorService.

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

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

huangapple
  • 本文由 发表于 2020年8月4日 20:26:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63246864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定