问题描述
我想编写一个异步方法,该方法返回 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?
CompletableFuture
itself returnsCompletableFuture<Void>
from many of its methods.java.nio
has aFuture<Void>
inAsynchronousSocketChannel
:Future<Void> connect(SocketAddress remote)
.- On the other hand,
java.util.concurrent
classes likeExecutorService
andScheduledExecutorService
returnFuture<?>
: for instance, withFuture<?> submit(Runnable task)
.
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< Void>或CompletableFuture<?> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!