[英]Exception propagation in java.util.concurrent.CompletableFuture
[英]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));
另一种选择是将whenComplete
与ExecutorService
一起使用。 如果您不使用 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.