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) ?
or you can use for {..} yield block to get sequence of Future. Future.sequence convert Seq[Future] to Future[Seq]
The futures are running concurrently because they have been started concurrently :). To run them sequentially you need to use flatMap:
Future.sequence just turns
Seq[Future[T]] => Future[Seq[T]]
which means gather results of all already started futures and put it in future .a little change to the original Future.sequence will make the future execution serialized:
and your code will look like this:
which is very like your original code and with same result collection with the original Future.sequence()
If you have a sequence of some values and you want to map them to
Future
's and execute them in series:Linearize:
From: https://gist.github.com/viktorklang/3347939