Return CompletableFuture< Void>或CompletableFuture<?> ;? [英] Return CompletableFuture<Void> or CompletableFuture<?>?
问题描述
我想编写一个异步方法,该方法返回 CompletableFuture
.未来的唯一目的是跟踪方法的完成时间,而不是结果.返回 CompletableFuture< Void>
或 CompletableFuture<?>
会更好吗?是否有理由偏爱另一个,或者它们可以互换?
-
CompletableFuture
本身从其许多方法返回CompletableFuture< Void>
. -
java.nio
在ExecutorService
和解决方案
最好使用 CompletableFuture< Void>
.
根据此答案由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<?> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!