簡體   English   中英

是否還有針對CompletableFuture的.thenCompose(),它也會異常執行?

[英]Is there a .thenCompose() for CompletableFuture that also executes exceptionally?

我想在另一個CompletableFuture完成后執行CompletableFuture ,無論第一個是否異常完成( .thenCompose()僅在執行正常時運行)。

例如:

CompletableFuture.supplyAsync(() -> 1L)
    .whenComplete((v, e) -> CompletableFuture.runAsync(() -> { 
        try {
            Thread.sleep(1000);
            System.out.println("HERE");
        } catch(InterruptedException exc) {
            return;
        }
    }))
    .whenComplete((v, e) -> System.out.println("ALL DONE"));

這打印

ALL DONE
HERE

我希望它是

HERE
ALL DONE

最好不要在第一個whenComplete()第二個whenComplete()

請注意,我不關心返回的結果/異常。

訣竅是使用.handle((r, e) -> r)來抑制錯誤:

CompletableFuture.runAsync(() -> { throw new RuntimeException(); })
    //Suppress error
    .handle((r, e) -> r)
    .thenCompose((r) -> 
         CompletableFuture.runAsync(() -> System.out.println("HELLO")));

也許您應該使用whenCompleteAsync而不是CompletableFuture.runAsync:

    CompletableFuture<Long> cf = CompletableFuture.supplyAsync(() -> 1L)
    .whenCompleteAsync((v, e) -> { 
        try {
            Thread.sleep(1000);
            System.out.println("HERE");
        } catch(InterruptedException exc) {
            //nothing
        }
        //check that thowing an exception also executes the next cf
        throw new RuntimeException("exception");
    })
    .whenCompleteAsync((v, e) -> System.out.println("ALL DONE (exception thrown: " + e + ")"));

    System.out.println("CF code finished");
    System.out.println(cf.get());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM