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

别说谁变了你拦得住时间么 提交于 2019-12-21 03:17:34

问题


I have seen an example in each of them, but I need to know exactly what is the difference in deep, Because sometimes I think I can use both of them to get the same result, So I want know so that I can choose the correct one?

what is the benefit of using each of them?

Like this example both are worked:

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.


回答1:


CompletionStage<T> is an interface which CompletabeFuture<T> is the only implementing class of this interface. By looking at the java doc for CompletionStage<T>, you'll notice the CompletionStage interface provides methods for taking one CompletionStage and transforming it into another CompletionStage. However, these objects being returned by the CompletionStages as actually themselves CompletabeFuture<T> objects.

So using CompletabeFuture<T> is kind of the same thing as using a CompletionStage<T> but the latter can be used as the base interface for possible new classes in the future as well as being a target type for many descending types just as we tend to do List<Integer> integerList = new ArrayList<>(); rather than ArrayList<Integer> integerList = new ArrayList<>();

you can have a read of the post introduction to CompletionStage and CompletableFuture for more details.




回答2:


A CompletableFuture is a CompletionStage. However, as its name suggests, it is

  • completable: It can be completed using complete or completeExceptionally.
  • a Future: You can use get method, etc. to get the result.

IMHO, in most APIs, like in your example, you should use CompletionStage, because

  • The implementation usually provides the mechanism to complete the stage. You don't need/want to expose methods like complete to the caller.
  • The caller is expected to use the returned value in an async manner instead of using blocking calls like get provided by Future.



回答3:


One is an interface and the other is a class. Usually you return the interface and not the implementation, but I doubt this is the case here. Returning CompletableFuture makes more sense for me.

Unless you are using some other implementation of that interface of course, like Spring's DelegatingCompletableFuture, but from your examples you are not.



来源:https://stackoverflow.com/questions/47571117/what-is-the-difference-between-completionstage-and-completablefuture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!