Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka Future - Parallel versus Concurrent?

Tags:

scala

akka

future

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?

like image 320
Kevin Meredith Avatar asked Mar 07 '16 16:03

Kevin Meredith


People also ask

How does Akka handle concurrency?

Akka's approach to handling concurrency is based on the Actor Model. In an actor-based system, everything is an actor, in much the same way that everything is an object in object-oriented design.

What is futures in Akka?

Introduction. In the Scala Standard Library, a Future is a data structure used to retrieve the result of some concurrent operation. This result can be accessed synchronously (blocking) or asynchronously (non-blocking). To be able to use this from Java, Akka provides a java friendly interface in akka.

Is Akka asynchronous?

Akka actors are asynchronous from the beginning. Reactive programs can be implemented in either way, synchronous and asynchronous.

Is Akka single threaded?

In Akka, actors are guaranteed to be run in a single-threaded illusion, which means that the Akka framework takes care of threading issues while allowing us to focus on the behavior that needs to be implemented. Actors may only communicate with each other and the outside world by through messages.


Video Answer


1 Answers

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)
      }
  }
like image 58
Rob Starling Avatar answered Oct 12 '22 23:10

Rob Starling