'CompletionStage' 和 'CompletableFuture' 有什么区别

What is the difference between 'CompletionStage' and 'CompletableFuture'

我在他们每个人中都看到了一个例子,但我需要确切地知道 deep 有什么区别,因为有时我认为我可以使用他们两个来获得相同的结果,所以我想知道这样我能选对吗?

使用它们各自有什么好处?

就像这个例子一样有效:

public CompletionStage<Result> getNextQueryUUID() {
    return CompletableFuture.supplyAsync(() -> {
        String nextId = dbRequestService.getNextRequestQueryUUID();
        return ok(nextId);
    }, executor);
}


public CompletableFuture<Result> getNextQueryUUID() {
    return CompletableFuture.supplyAsync(() -> {
        String nextId = dbRequestService.getNextRequestQueryUUID();
        return ok(nextId);
    }, executor);
}

This example run in Play framework.

CompletionStage<T> is an interface of which CompletableFuture<T> 是目前唯一的实施 class。通过查看 CompletionStage<T> 的 javadoc,您会注意到它提供了将一个 CompletionStage<T> 转换为另一个 CompletionStage<T> 的方法。但是,CompletionStage<T> 的返回值实际上是 CompletabeFuture<T> 个对象。

所以使用 CompletabeFuture<T> 与使用 CompletionStage<T> 有点相同,但后者也可以用作将来可能的新 classes 的基础接口作为许多降序类型的目标类型,就像我们倾向于 List<Integer> integerList = new ArrayList<>(); 而不是 ArrayList<Integer> integerList = new ArrayList<>();

一个是接口,一个是class。通常你 return 接口而不是实现,但我怀疑这里是这种情况。返回 CompletableFuture 对我来说更有意义。

除非您当然正在使用该接口的其他实现,例如Spring的DelegatingCompletableFuture,但从您的示例来看您不是。

一个CompletableFuture是一个CompletionStage。然而,顾名思义,它是

  • 可完成:可以使用completecompleteExceptionally.
  • a Future:可以使用get等方法得到结果

恕我直言,在大多数 API 中,就像在您的示例中一样,您应该使用 CompletionStage,因为

  • 实现通常提供完成阶段的机制。您不会 need/want 将 complete 之类的方法公开给调用者。
  • 调用方应以异步方式使用返回值,而不是使用 Future 提供的 get 等阻塞调用。