簡體   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