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

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

What is the advantage of using each of them?

As in this example, both work:

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 runs on the Play framework .

+7
java concurrency completable-future
source share
3 answers

CompletionStage<T> is the interface that CompletabeFuture<T> is the only class that implements this interface. Looking at the java document for CompletionStage<T> , you will notice that the CompletionStage interface provides methods for taking one CompletionStage and converting it to another CompletionStage . However, these objects are returned by CompletionStages as CompletabeFuture<T> objects themselves.

Thus, using CompletabeFuture<T> similar to using CompletionStage<T> , but the latter can be used as the base interface for possible new classes in the future, and also be the target type for many descending types, just like we tend to do List<Integer> integerList = new ArrayList<>(); , not ArrayList<Integer> integerList = new ArrayList<>();

You can read the introduction to CompletionStage and CompletableFuture for more details.

+3
source share

One is the interface, and the other is the class. You usually return an interface, not an implementation, but I doubt that this is the case here. Returning CompletableFuture makes more sense to me.

Unless, of course, you are using some other implementation of this interface, for example Spring DelegatingCompletableFuture , but from your examples you do not.

+1
source share

A CompletableFuture is a CompletionStage . However, as its name implies, this

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

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

  • An implementation typically provides a mechanism for completing a step. You do not need / do not want to call methods like complete caller.
  • The caller is expected to use the return value in asynchronous mode instead of using blocking calls of type get provided by Future .
0
source share

All Articles