简体   繁体   中英

Chain few CompletableFuture operations

I have few separate operations that i want to chain in the same style like we have for Promises in JS.

So currently i have such code:

    CompletableFuture<Data1> data1 = ...;
    CompletableFuture<Data2> data2 = ...;

    // Fetch in parallel!
    CompletableFuture.allOf(
            data1,
            data2
    ).join(); // wait 2 threads to finish

    CompletableFuture<Data3> data3 = ... // i need data1 here
    data3.join();

Is it possible to rewrite it in one chain ? Kind of:

CompletableFuture.allOf(
        data1,
        data2
)
.then((result1, result2) -> return another CompletableFuture)
.then(result3 -> { ...do other stuff here})

When using allOf , there is no way around calling join on the input futures to get the values in a dependent function (though you'll know that these calls won't block).

However, when you have exactly two futures to combine, there is no need to use allOf ; you can combine them smoothly:

CompletableFuture<FinalResult> f = data1
    .thenCombine(data2, (result1, result2) -> another CompletableFuture)
    .thenCompose(Function.identity())
    .thenAccept(result3 -> …);

thenAccept will evaluate a function mapping a result value to a new result value, whereas thenCompose will evaluate a function mapping a result value to a new future. The method thenCombine is the two-future variant of thenAccept , allowing to map two values to a new value.

But there is no two-future variant of thenCombine , so the solution is to treat the future created from the two intermediate values like a value (getting a future of a future), followed by thenCompose(Function.identity()) to map the “value” to a future. Then, we can chain a function for processing the third result, once the future has been completed.

CompletableFuture.allOf(...) returns a CompletableFuture<Void> . It knows nothing about the types that will be returned by the givne CompletableFuture s:

the results, if any, of the given CompletableFuture s are not reflected in the returned CompletableFuture , but may be obtained by inspecting them individually.

So you will have to get the returned values of data1 and data2 if you want to use them.

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