【发布时间】:2021-02-04 17:58:45
【问题描述】:
使用 Scala 2.13.0:
implicit val ec = ExecutionContext.global
val arr = (0 until 20).toIterator
.map { x =>
Thread.sleep(500);
println(x);
x
}
val fss = arr.map { slowX =>
Future { blocking { slowX } }
}
Await.result(Future.sequence(fss), Inf)
问题
arr 是一个迭代器,其中每个项目需要 500 毫秒的处理时间。我们用Future { blocking { ... }} 映射迭代器,目的是使处理并行(使用全局执行上下文)。最后我们运行Future.sequence
使用迭代器。
给定Future.apply[T](body: =>T)和blocking[T](body: =>T)的定义,body是惰性传递的,这意味着body将在Future中被处理。如果我们在Iterator.map的定义中注入它,我们得到def next() = Future{blocking(self.next())},所以迭代器的每一项都应该在Future中处理。
但是当我尝试这个示例时,我可以看到迭代器是按顺序使用的,这不是预期的!
这是一个 Scala 错误吗?还是我错过了什么?
【问题讨论】:
-
arr.map在传递给Future之前计算前一个map中的值,因此sleep发生在Future之外
标签: scala