首页 > 解决方案 > 等待期货列表 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的个体提交给方法有什么好处?FuturedoSomething()result

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

标签: scalafuture

解决方案


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


推荐阅读