英文:
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<Throwable> exception = new CopyOnWriteArraySet<>();
CompletableFuture.runAsync(() -> {
}).whenComplete((method, e) -> 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(() -> {
}).whenCompleteAsync((method, throwable) -> {
// throw or handle in some way on main thread
}, mainThread);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论