zt1983811 zt1983811 -4 years ago 68
Scala Question

Convert Scala Future and Promise to Java 8 ComletableFuture

I have read the Scala Future and Promise and this post in stackoverflow, I understand the concept is that

You can think of futures and promises as two different sides of a pipe. On the promise side, data is pushed in, and on the future side, data can be pulled out.

Right now I am wondering how to do the same thing using Java 8's

Example code:

Promise<String> promise = new Promise.DefaultPromise<>();
listOfString.stream().forEach(oneString -> {
..... some other computation here ....
promise.future().map(new Mapfunction{...});

I am wondering how to use Java 8
to achieve the same, because I think
does not really have data push in and data push out concept like Scala promise does.

Answer Source

In Java 8 CompletableFuture is the "write" side of the computation, whereas CompletionStage is the "read" side.

So for example:

CompletableFuture<String> fut = new CompletableFuture<String>();
listOfString.stream().forEach(oneString -> {
// do some stuff (possibily asynchronously)
// and then complete the future
fut.thenApply(/* some computation */);

Now, since CompletableFuture extends CompletionStage you can pass around the fut instance as a CompletionStage and your users will be able to attach async actions to perform once it complets.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download