创建已完成的 CompletableFuture<Void> 的正确方法是什么

What is the correct way to create an already-completed CompletableFuture<Void>

我在 java 8 中使用 Completable futures,我想编写一个方法,根据收到的参数,并行运行多个具有副作用的任务,然后 return 它们的 "combined" 未来(使用 CompletableFuture.allOf()),或者什么都不做并且 return 是一个已经完成的未来。

然而,allOf return 是 CompletableFuture<Void>:

public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)

创建已知的已完成未来的唯一方法是使用 completedFuture(),它需要一个值:

public static <U> CompletableFuture<U> completedFuture(U value)

Returns a new CompletableFuture that is already completed with the given value.

Void 是不可实例化的,所以我需要另一种方法来创建一个已经完成的 CompletableFuture<Void>.

类型的未来

最好的方法是什么?

传一个null我猜:

CompletableFuture<Void> done = CompletableFuture.completedFuture(null);

由于 Void 无法实例化,您只能完成一个 CompletableFuture<Void>null 结果,这正是您在调用 join() 时也会得到的结果在成功完成后 allOf() 返回的未来。

所以你可以使用

CompletableFuture<Void> cf = CompletableFuture.completedFuture(null);

得到这样一个已经完成的未来

不过你也可以使用

CompletableFuture<Void> cf = CompletableFuture.allOf();

表示没有结果依赖的作业。结果将完全相同。