[英]What is the correct way to create an already-completed CompletableFuture<Void>
I am using Completable futures in java 8 and I want to write a method that, based on a received parameter, either runs multiple tasks with side effects in parallel and then return their "combined" future (using CompletableFuture.allOf()
), or does nothing and returns an already-completed future. 我在java 8中使用Completable future我想编写一个方法,根据接收到的参数,并行运行多个具有副作用的任务,然后返回它们的“组合”未来(使用
CompletableFuture.allOf()
),或者什么都不做,并回归已经完成的未来。
However, allOf
returns a CompletableFuture<Void>
: 但是,
allOf
返回CompletableFuture<Void>
:
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
And the only way to create an already-completed future that know is using completedFuture()
, which expects a value: 创建已经完成的未来的唯一方法就是使用
completedFuture()
,它需要一个值:
public static <U> CompletableFuture<U> completedFuture(U value)
Returns a new CompletableFuture that is already completed with the given value.
返回已使用给定值完成的新CompletableFuture。
and Void
is uninstantiable, so I need another way to create an already-completed future of type CompletableFuture<Void>
. 并且
Void
是不可实现的,所以我需要另一种方法来创建CompletableFuture<Void>
类型的已完成的未来。
What is the best way to do this? 做这个的最好方式是什么?
Since Void
can not be instantiated, you can only complete a CompletableFuture<Void>
with a null
result, which is exactly what you also will get when calling join()
on the future returned by allOf()
once it has been successfully completed. 由于无法实例化
Void
,因此只能使用null
结果完成CompletableFuture<Void>
,这正是在成功完成allOf()
返回的未来调用join()
时也会得到的结果。
So you can use 所以你可以使用
CompletableFuture<Void> cf = CompletableFuture.completedFuture(null);
to get such an already completed future. 获得这样一个已经完成的未来。
But you can also use 但你也可以使用
CompletableFuture<Void> cf = CompletableFuture.allOf();
to denote that there are no jobs the result depends on. 表示没有结果取决于的工作。 The result will be exactly the same.
结果将完全相同。
传递一个null
我猜:
CompletableFuture<Void> done = CompletableFuture.completedFuture(null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.