创建已经完成的CompletableFuture< Void>的正确方法是什么? [英] What is the correct way to create an already-completed CompletableFuture<Void>

查看:982
本文介绍了创建已经完成的CompletableFuture< Void>的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Java 8中使用Completable future,并且我想编写一种方法,该方法基于接收到的参数并行运行具有副作用的多个任务,然后返回其合并的" future(使用CompletableFuture.allOf()),或什么也不做,并返回一个已经完成的未来.

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.

但是,allOf返回一个CompletableFuture<Void>:

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

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

And the only way to create an already-completed future that know is using completedFuture(), which expects a value:

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

返回一个已经完成并具有给定值的新CompletableFuture.

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

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

and Void is uninstantiable, so I need another way to create an already-completed future of type CompletableFuture<Void>.

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

由于无法实例化Void,因此只能用null结果完成CompletableFuture<Void>,而这恰恰是在得到null结果时得到的结果.成功完成后,在allOf()返回的将来调用join().

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.

因此您可以使用

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

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

to get such an already completed future.

但是您也可以使用

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

表示不存在结果依赖的作业.结果将完全相同.

to denote that there are no jobs the result depends on. The result will be exactly the same.

这篇关于创建已经完成的CompletableFuture&lt; Void&gt;的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆