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 works:
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
.
A
CompletableFuture
is aCompletionStage
. However, as its name suggests, it iscomplete
orcompleteExceptionally
.Future
: You can useget
method, etc. to get the result.IMHO, in most APIs, like in your example, you should use
CompletionStage
, becausecomplete
to the caller.get
provided byFuture
.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.CompletionStage<T>
is an interface of whichCompletabeFuture<T>
is the only current implementing class. By looking at the javadoc forCompletionStage<T>
, you'll notice it provides methods for taking oneCompletionStage<T>
and transforming it into anotherCompletionStage<T>
. However, the returned values by theCompletionStage<T>
are actually themselvesCompletabeFuture<T>
objects.So using
CompletabeFuture<T>
is kind of the same thing as using aCompletionStage<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 doList<Integer> integerList = new ArrayList<>();
rather thanArrayList<Integer> integerList = new ArrayList<>();
You can read the post introduction to CompletionStage and CompletableFuture for more details.