Return CompletableFuture or CompletableFuture<?>?

后端 未结 4 1508
予麋鹿
予麋鹿 2021-01-30 12:35

I want to write an asynchronous method that returns a CompletableFuture. The only purpose of the future is to track when the method is complete, not its result. Would it be bett

4条回答
  •  渐次进展
    2021-01-30 13:18

    The suitable type depends on its semantic. All listed options promise to signal completion and may asynchronously return exceptions.

    • CompletableFuture: The Void tells the user there is no result to be expected.
    • CompletableFuture The ? means the type of the contains value is undefined in the sense that any value could be delivered.

    The CompletableFuture class inherits several convenience methods from CompletionStage. But it does also allow the caller of your method to trigger completion of the future which seems wrong because your method is responsible to signal its completion itself. There is also a cancel(...) method which is pretty pointless in the default implementation of CompletableFuture as it does not cancel the execution.

    • Future: The Void tells the user there is no result to be expected.
    • Future The ? means the type of the contains value is undefined in the sense that any value could be delivered.

    Future lacks the convenience methods from CompletionStage. It does not allow to trigger completion of the future but the execution can be cancelled.

    Next option is CompletionStage:

    • CompletionStage: The Void tells the user there is no result to be expected. The convenience methods to bind handlers are present but the cancel(...) method is not. The caller of your method cannot trigger the completion of a CompletionStage.
    • & CompletionStage>: Set of methods from Future and CompletionStage. It tells that there is no result, convenience methods are present as well as the option to cancel. The caller of your method cannot trigger the completion of a CompletionStage.

    The absence of the cancel(...) method might fit your scenario or not. Therefore I suggest to go with CompletionStage if you don't need cancellation and use & CompletionStage> if you require the option to cancel the execution. If you chose & CompletionStage> you probably want to create an interface yourself that inherits from Future and CompletionStage to be used as return type instead of putting the long type intersection directly in your method declaration.

    You should avoid returning with a declared return type CompletableFuture because of the possibility for the caller to trigger completion of the future. Doing so deliberately leads to confusing code and surprising hangs because it is not clear which code is responsible to trigger completion anymore. Use one of the mentioned more restricted types to let the type system prevent unintentional completion triggering by the caller of your method.

提交回复
热议问题