scala - 等待期货列表 VS 等待单个期货
问题描述
我试图了解以下两种方法的优缺点(如果有的话)
def doSomething(): Future[Unit] = ???
// Create one big list of futures and wait on this future
private val oneBigFuture: Future[immutable.IndexedSeq[Unit]] = Future.sequence {
(1 to 1000).map(_ => doSomething)
}
Await.result(oneBigFuture, 10.seconds)
// Wait on the individual futures created by the doSomething() method
(1 to 1000).foreach {
_ =>
val individualFuture = doSomething()
Await.result(individualFuture, 10.seconds)
}
创建一个大的期货列表并将其提交给方法而不是将方法产生result
的个体提交给方法有什么好处?Future
doSomething()
result
显然,第一种方法创建了一个批处理操作,但我不确定编译器是否也将第二种方法转换为批处理操作 - 因为它包含在一个foreach
语句中。
解决方案
第一种方法应该快得多,因为所有Future
s 都在阻塞发生之前启动,而在第二种方法中,阻塞发生在每次下一次Future
启动之前。你可以这样测试
def doSomething(): Future[Unit] = Future { Thread.sleep(1000); println(1) }
在哪里
Await.result(Future.sequence((1 to 10).map(_ => doSomething())), Duration.Inf)
大约需要一秒钟,而
(1 to 10).foreach(_ => Await.result(doSomething(), Duration.Inf))
大约需要 10 秒。
推荐阅读
- spring-boot - 添加执行器的依赖项后,Spring Boot 无法正常工作
- docker - 为 centos 8 容器设置 php-fpm
- flutter - 在 POST 请求后更新显示的数据
- email - smtp 错误:535 5.7.8 Go 中的 gmail 不接受用户名和密码
- java - 在 Java 中使用 ProcessBuilder 读取输出 git-bash
- php - 有没有更好的方法来测试嵌套数组中是否存在使用 twig 的值
- python - 将某些值从一个列表更改为另一个 python
- excel - 复制没有公式的整个 Excel 工作表
- mongodb - Docker 撰写镜像文件夹
- visual-studio-code - VScode:编辑时执行最后一个终端命令的热键?