Scala 等待一系列期货与等待单个期货

Scala 等待一系列期货与等待单个期货,scala,future,Scala,Future,我试图了解以下两种方法的利弊(如果有的话) 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)

我试图了解以下两种方法的利弊(如果有的话)

  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)
  }
创建一个大型期货列表并将其提交给
结果
方法,而不是将
doSomething()
方法生成的单个
期货
提交给
结果
方法,有什么好处


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

第一种方法应该快得多,因为所有
未来的
都是在阻塞发生之前启动的,而在第二种方法中,阻塞发生在下一次
未来开始之前。你可以这样测试

def doSomething(): Future[Unit] = Future { Thread.sleep(1000); println(1) }
在哪里

大约需要一秒钟

(1 to 10).foreach(_ => Await.result(doSomething(), Duration.Inf))

大约需要10秒。

第一次进近应该快得多,因为所有的
未来
都是在阻塞发生之前开始的,而在第二次进近中,阻塞发生在下一次
未来
开始之前。你可以这样测试

def doSomething(): Future[Unit] = Future { Thread.sleep(1000); println(1) }
在哪里

大约需要一秒钟

(1 to 10).foreach(_ => Await.result(doSomething(), Duration.Inf))

大约需要10秒钟。

这两种操作都不是批处理操作,编译器不会执行任何操作,等待是一种不好的做法。您应该使用对您的程序更有意义的方法,通常情况下,操作包含所有结果的列表的未来比操作未来列表更容易。批处理操作也不是,编译器不会执行任何操作,等待是一种不好的做法。你应该使用一个对你的程序更有意义的方法,通常情况下,操作一个包含所有结果的列表的未来比操作一个未来列表更容易。