Akka

concurrency and parallelism

Andraž Bajt / @edofic

Concurrency vs Parallelism

Concurrency: two tasks running

Parallelism: two things running at the same time

Threads

  • Good for OS/processor
  • Bad for programmer
  • Deadlocks, race conditions, synchronization
  • "Impossible" to get right

Callbacks

  • Node.js is popular
  • Impure
  • Error handling
  • Unreadable

The Actor Model

  • Carl Hewitt 1973
  • Erricoson Erlang in 80s

Different take on OO

Sample

Defining actors


import akka.actor._

case class DoStuff(s: String)

class Worker extends Actor {
  def receive = {
    case DoStuff(s) => doStuff(s)
    case msg: String => println(msg)
    case 42 => sender ! "You'll need a bigger computer for that"
  }

  def doStuff(s: String) = ... //some blocking operation
}
                      

Sample

Usage


import akka.actor._
import akka.pattern.ask

val sys = ActorSystem()
val worker = sys.actorOf(Props[Worker])

worker ! DoStuff("details")
worker ! "hello world"
val question: Future[Question] = worker ? 42
                    

Routing


import akka.routing.RoundRobin
val worker = sys.actorOf(
  Props[Worker] withRouter RoundRobin(5),
  "myWorker"
)
                  

Config

Exact same code!


akka.actor.deployment {
  /myWorker {
    router = random-router
    nr-of-instances = 17
  }
}
                  

Going remote

Just change the config

  • remote deploy
  • remote actor lookup

Cluster

  • cluster aware routers
  • no code changes

Call now and get these for free

  • Typed actors
  • Logging
  • Event bus
  • Scheduling
  • Dataflow model
  • Agents
  • Transactions
  • IO
  • ...

See http://akka.io/