Whether there is a. ThenCompose () for CompletedFuture, which also runs exclusively?

I want to execute CompletableFutureonce when it finishes CompletableFuture, regardless of whether the first of them finishes exclusively (it .thenCompose()is executed only when completion is complete).

For instance:

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"));

Will print

ALL DONE
HERE

and I would like him to be

HERE
ALL DONE

preferably without inserting the second whenComplete()inside the first.

Please note that here I am not interested in the returned result / exception.

+4
source share
2 answers

The trick is to use .handle((r, e) -> r)to suppress the error:

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

, ifCompleteAsync 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());
0

Source: https://habr.com/ru/post/1568422/


All Articles