简体   繁体   中英

Issue with Completablefuture exception handling

I have 2 completableFuture (cf), I need to run them sequentially and "B" should run only if "A" is complete and should not run if A fails for any reason.

My code looks like this :

CompletableFuture<String> f = CompletableFuture.supplyAsync( () -> doA(arg)).whenComplete(() -> doB(arg));

With the above, doB runs even when doA throws an exception. How should I handle this?

Taking a quick look at the documentation of CompletableFuture shows that the whenComplete method always runs the given BiConsumer , even if execution wasn't successful (ie if it just finishes executing):

Returns a new CompletionStage with the same result or exception as this stage, that executes the given action when this stage completes.

The method that you're looking for is thenRun :

Returns a new CompletionStage that, when this stage completes normally, executes the given action. See the CompletionStage documentation for rules covering exceptional completion.

Which only runs the given Runnable if the previous stage ( doA() in your case) executes successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM