繁体   English   中英

等待期货列表 VS 等待单个期货

[英]Waiting on a list of futures VS Waiting on individual futures

我试图了解以下两种方法的优缺点(如果有的话)

  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)
  }

创建一个大的 future 列表并将其提交给result方法而不是将doSomething()方法生成的单个Future提交给result方法有什么好处?

显然,第一种方法创建了一个批处理操作,但我不确定编译器是否也将第二种方法转换为批处理操作 - 因为它包裹在foreach语句中。

第一种方法应该更快,因为所有Future都在阻塞发生之前启动,而在第二种方法中,阻塞发生在每个下一个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 秒。

暂无
暂无

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

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