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

前端 未结 3 566
盖世英雄少女心
盖世英雄少女心 2020-12-30 21: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, S

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 22:24

    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.

提交回复
热议问题