[英]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.