将 Scala Future 和 Promise 转换为 Java 8 ComletableFuture

Convert Scala Future and Promise to Java 8 ComletableFuture

我看过Scala Future and Promise and this post in Whosebug,我理解的概念是

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.

现在我想知道如何使用 Java 8 的 CompletableFuture 来做同样的事情。

示例代码:

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

我想知道如何使用 Java 8 CompletableFuture 来实现相同的目的,因为我认为 CompletableFuture 并没有像 Scala promise 那样真正有数据推入和数据推出的概念

在Java8中CompletableFuture是计算的"write"端,而CompletionStage是"read"端。

例如:

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

现在,由于 CompletableFuture 扩展了 CompletionStage,您可以将 fut 实例作为 CompletionStage 传递,您的用户将能够附加异步操作以执行一次它完成了。