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
?
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`.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With