5

From the well-written Akka Concurrency:

enter image description here

As I understand, the diagram points out, both numSummer and charConcat will run on the same thread.

Is it possible to run each Future in parallel, i.e. on separate threads?

Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
  • 2
    Arguably, the figure should be called "Flatmapping concurrently versus sequentially", given that the left one is the concurrent one.... – mdm Mar 07 '16 at 17:23
  • But `concurrent` implies re-using the same thread, no? – Kevin Meredith Mar 07 '16 at 17:27
  • Not necessarily, as far as I understand it. http://stackoverflow.com/questions/1897993/difference-between-concurrent-programming-and-parallel-programming or https://blogs.oracle.com/yuanlin/entry/concurrency_vs_parallelism_concurrent_programming; sequential would be when there is no overlap between executions. – mdm Mar 07 '16 at 17:32

1 Answers1

11

The picture on the left is them running in parallel.

The point of the illustration is that the Future.apply method is what kicks off the execution, so if it doesn't happen until the first future's result is flatMaped (as in the picture on the right), then you don't get the parallel execution.

(Note that by "kicked off", i mean the relevant ExecutionContext is told about the job. How it parallelizes is a different question and may depend on things like the size of its thread pool.)

Equivalent code for the left:

val numSummer = Future { ... }  // execution kicked off
val charConcat = Future { ... }  // execution kicked off
numSummer.flatMap { numsum =>
  charConcat.map { string =>
    (numsum, string)
  }
}

and for the right:

Future { ... }  // execution kicked off
  .flatMap { numsum =>
    Future { ... }  // execution kicked off (Note that this does not happen until
                    // the first future's result (`numsum`) is available.)
      .map { string =>
        (numsum, string)
      }
  }
Rob Starling
  • 3,868
  • 3
  • 23
  • 40