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

Ebraheem Alrabee' :

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.

Ousmane D. :

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 read the post introduction to CompletionStage and CompletableFuture for more details.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=428462&siteId=1