[英]Waiting on a list of futures VS Waiting on individual futures
I am trying to understand the pros and cons - if any - of the following two approaches我试图了解以下两种方法的优缺点(如果有的话)
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)
}
What is the benefit of creating one big list of futures and submitting this to the result
method instead of submitting the individual Future
s produced by the doSomething()
method to the result
method?创建一个大的 future 列表并将其提交给result
方法而不是将doSomething()
方法生成的单个Future
提交给result
方法有什么好处?
Obviously the first approach creates a batch operation but I am not sure if the compiler converts the second approach into a batch operation as well - since it's wrapped around a foreach
statement.显然,第一种方法创建了一个批处理操作,但我不确定编译器是否也将第二种方法转换为批处理操作 - 因为它包裹在foreach
语句中。
The first approach should be much faster because all the Future
s are started before blocking occurs, whilst in the second approach blocking occurs before each next Future
starts.第一种方法应该更快,因为所有Future
都在阻塞发生之前启动,而在第二种方法中,阻塞发生在每个下一个Future
开始之前。 You can test this like so你可以这样测试
def doSomething(): Future[Unit] = Future { Thread.sleep(1000); println(1) }
where在哪里
Await.result(Future.sequence((1 to 10).map(_ => doSomething())), Duration.Inf)
would take about a second, whilst大约需要一秒钟,而
(1 to 10).foreach(_ => Await.result(doSomething(), Duration.Inf))
would take about 10 seconds.大约需要 10 秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.