简体   繁体   English

等待Scala中任何给定的期货?

[英]Wait for any of given Futures in Scala?

Suppose I need to execute a few parallel tasks in Scala. 假设我需要在Scala中执行一些并行任务。 Each task performs some blocking call (eg Process.waitFor ). 每个任务都执行一些阻塞调用(例如Process.waitFor )。 Now I would like to wait until any of the tasks completes. 现在我想等到任何任务完成。

As I understand I should use Scala Future to wrap the task. 据我所知,我应该使用Scala Future来包装任务。 Is there any API in Scala to wait until any of given Futures finishes? Scala中是否有任何API等待任何给定的Futures结束?

There is build-in method for doing this: 有这样做的内置方法:

Future.firstCompletedOf(yourFutures)

from the doc : 来自文档

Returns a Future to the result of the first future in the list that is completed. 返回完成列表中第一个未来结果的Future。

Note that this would not interrupt all other futures so you have cancel them by yourself, if you need to. 请注意,这不会打断所有其他期货,因此如果需要,您可以自行取消它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM