本文介绍了Return CompletableFuture< Void>或CompletableFuture<?&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个异步方法,该方法返回 CompletableFuture .未来的唯一目的是跟踪方法的完成时间,而不是结果.返回 CompletableFuture< Void> CompletableFuture<?> 会更好吗?是否有理由偏爱另一个,或者它们可以互换?

  • CompletableFuture 本身从其许多方法返回 CompletableFuture< Void> .
  • java.nio 在: Future< Void>connect(SocketAddress远程).
  • 另一方面, java.util.concurrent 类,例如和返回 Future<?> :例如,使用 Future<?>提交(可运行任务).

请注意,我只问的是返回类型,而不是参数列表,变量声明或其他上下文.

解决方案

最好使用 CompletableFuture< Void> .

根据此答案由, Future<?> 是一个较小的API缺陷.在Java 6中, submit()方法在内部使用了 Future< Object> ,因此其返回类型设置为 Future<?> .在Java 7中,实现更改为在内部使用 Future< Void> ,但是更改API为时已晚,因此返回值保持为 Future<?> ./p>

较新的Java API使用 Future< Void> CompletableFuture< Void> .这些是我们应该遵循的示例.

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 better to return CompletableFuture<Void> or CompletableFuture<?>? Is there a reason to prefer one or the other, or are they interchangeable?

Note that I'm only asking about return types, not parameter lists, variable declarations, or other contexts.

解决方案

It is best to use CompletableFuture<Void>.

According to this answer found by Sotirios Delimanolis, Future<?> is a minor API flaw. In Java 6 the submit() method used a Future<Object> internally, and so its return type was set to Future<?>. In Java 7 the implementation changed to use Future<Void> internally, but it was too late to change the API so the return value stayed as Future<?>.

Newer Java APIs use Future<Void> and CompletableFuture<Void>. Those are the examples we should follow.

这篇关于Return CompletableFuture&lt; Void&gt;或CompletableFuture&lt;?&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:40
查看更多