sscarduzio sscarduzio - 3 months ago 15
Scala Question

Why Future.sequence executes my futures in parallel rather than in series?

The word "sequence" means a series of actions one after the other.

object Test {

def main(args: Array[String]) {

def producer() = {
val list = Seq(
future { println("startFirst"); Thread.sleep(3000); println("stopFirst") },
future { println("startSecond"); Thread.sleep(1000); println("stopSecond") }
)
Future.sequence(list)
}

Await.result(producer, Duration.Inf)
}
}


Therefore I expect this program to print:

startFirst
stopFirst
startSecond
stopSecond


or even:

startSecond
stopSecond
startFirst
stopFirst


but not (as it happens):

startFirst
startSecond
stopSecond
stopFirst


Why this method is not called
Future.parallel()
?
And what should I use to guarantee that all futures in a
Seq
of futures are triggered serially (as opposed to in parallel) ?

Answer

The futures are running concurrently because they have been started concurrently :). To run them sequentially you need to use flatMap:

Future { println("startFirst"); 
         Thread.sleep(3000); 
         println("stopFirst") 
        }.flatMap{
         _ =>  Future { 
                       println("startSecond"); 
                       Thread.sleep(1000); 
                       println("stopSecond") 
               }
        }

Future.sequence just turns Seq[Future[T]] => Future[Seq[T]] which means gather results of all already started futures and put it in future .

Comments