简体   繁体   中英

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?

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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