Return CompletableFuture or CompletableFuture<?>?

后端 未结 4 1441
予麋鹿
予麋鹿 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:22

    Looking at the CompletableFuture API you will find that CompletableFuture is used with side effects kind of methods where the result can't be obtained (because it doesn't exist), ex:

    CompletableFuture.runAsync(Runnable runnable);
    

    returning a CompletableFuture here would be confusing because there no result really, we only care about the completion. Methods that take Consumers and Runnables return CompletableFuture, ex : thenAccept, thenAcceptAsync. Consumer and Runnable are used for side effects in general.

    Another use case for Void is when you really don't know the result. For example: CompletableFuture.allOf, the passed list might be a CompletableFuture originated from a Runnable, so we can't get the result.

    Having said all of that, CompletableFuture is only good if you don't have another option, if you can return the result then please go for it, the caller might choose to discard if they are not interested. You said that you are only interested in the completion, then yes, CompletableFuture would do the job, but your API users would hate you if they know that CompletableFuture was an option and you just decided on their behalf that they will never need the result.

    提交回复
    热议问题