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, S
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 which CompletableFuture<T> is the only current implementing class. By looking at the javadoc for CompletionStage<T>
, you'll notice it provides methods for taking one CompletionStage<T>
and transforming it into another CompletionStage<T>
. However, the returned values by the CompletionStage<T>
are 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 read the post introduction to CompletionStage and CompletableFuture for more details.
A CompletableFuture
is a CompletionStage
. However, as its name suggests, it is
complete
or
completeExceptionally
.Future
: You can use get
method, etc. to get the result.IMHO, in most APIs, like in your example, you should use CompletionStage
, because
complete
to the caller.get
provided by Future
.