Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the execution order (sequential or concurrent) of futures inside of for comprehension?

Tags:

scala

akka

future

val f: Future[Result] =
   for {
       x <- ask(actorA, Request).mapTo[Int] // call pattern directly
       s <- (actorB ask Request).mapTo[String] // call by implicit conversion
       d <- (actorC ? Request).mapTo[Double] // call by symbolic name
  } yield Result(x, s, d)

I wanted to know if the 3 futures inside the for-comprehension are running concurrenty or not. It's an snippet extracted from AKKA doc. My guess is that the're sequential as they get translated into nested flatmaps/maps. Thanks!

like image 675
user3799078 Avatar asked Jul 02 '14 19:07

user3799078


1 Answers

These futures do not run concurrently, they run serially one after another.

This for-comprehension first executes ask(actorA, Request).mapTo[Int]. Until this future gets completed, the next generator in the for-comprehension is not executed.

Only after ask(actorA, Request).mapTo[Int] is completed, the next line of the for-comprehension, (actorB ask Request).mapTo[String], is executed.

And once that future is completed, the third expression in the for-comprehension is evaluated, and the third future is started.

To have these futures run concurrently, you would have to start all three futures first, and only use them in the for-comprehension after that:

val fut1 = ask(actorA, Request).mapTo[Int]
val fut2 = (actorB ask Request).mapTo[String]
val fut3 = (actorB ask Request).mapTo[String]

for {
  x <- fut1
  s <- fut2
  d <- fut3
} yield Result(x, s, d)
like image 115
axel22 Avatar answered Oct 28 '22 21:10

axel22