Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break the flow of CompletableFuture

I have certain flow that runs async using the CompletableFuture, e.g.:

foo(...)
        .thenAccept(aaa -> {
            if (aaa == null) {
                 break!
            }
            else {
              ...
            }
        })
        .thenApply(aaa -> {
           ...
        })
        .thenApply(...

So if my foo() returns null (in a future) I need to break very soon, otherwise, the flow continue.

For now I have to check for null all the way, in every future block; but that is ugly.

Would this be possible with CompletableFuture?

EDIT

With CompletableFuture you can define your flow of async tasks, that are executed one after the other. For example, you may say:

Do A, and when A finishes, do B, and then do C...

My question is about breaking this flow and saying:

Do A, but if result is null break; otherwise do B, and then do C...

This is what I meant by 'breaking the flow`.

like image 267
igr Avatar asked Jun 29 '15 20:06

igr


People also ask

How do I interrupt CompletableFuture?

As such, there's nothing you can do through CompletableFuture to interrupt any thread that may be running some task that will complete it. You'll have to write your own logic which tracks any Thread instances which acquire a reference to the CompletableFuture with the intention to complete it.

Is CompletableFuture get blocking?

It just provides a get() method which blocks until the result is available to the main thread. Ultimately, it restricts users from applying any further action on the result. You can create an asynchronous workflow with CompletableFuture. It allows chaining multiple APIs, sending ones to result to another.

Is CompletableFuture asynchronous?

CompletableFuture is at the same time a building block and a framework, with about 50 different methods for composing, combining, and executing asynchronous computation steps and handling errors. Such a large API can be overwhelming, but these mostly fall in several clear and distinct use cases.


1 Answers

Your question is very general, so the answer might not exactly apply to you. There are many different ways to address this that might be appropriate in different situations.

One way to create a branch in evaluation of CompletableFuture is with .thenCompose:

foo().thenCompose(x -> x == null
        ? completedFuture(null)
        : completedFuture(x)
            .then.....(...)
            .then.....(...)
).join();
like image 133
Misha Avatar answered Sep 29 '22 23:09

Misha