2. Challenges with Concurrency
• Amdhal’s law
• Shared state
• Locking, concurrency
protocols
• Only way to increase
execution speed
http://en.wikipedia.org/w/index.php?title=File:AmdahlsLaw.svg
3. Actors
• Unit of computation, encapsulates
• Processing
• Storage
• Communication
• 3 axioms. An actor can:
• Create new actors
• Send messages to actors it knows about
• Handle incoming messages
4. Actors in practice
• Actors maintain internal state
• Promise: Only one thread can process
msgs for a single actor at any time
• Actors have mailboxes
• Messages must be immutable
• Actors are supervised by other actors
6. Actors in practice
• Work in a container
• Actor registry
• Manages assignment of actors to
processors
• Fault tolerance, supervision
• Can be distributed (explicitly/implicitly)
• Can be hot swapped
7. A simple Actor
case class Msg(contents: String)
class ActorExample extends Actor {
def receive = {
case Msg(contents) => print(contents)
case _ => "Don't know what to do"
}
}
8. An Actor with state
case object Add
case object Added
class ActorExample extends Actor {
var state = 0
def receive = {
case Add =>
state += 1
sender ! Added
case _ => "Don't know what to do with it"
}
}
9. Types of
communication
• Fire and forget
• Fire and get Future
• Fire and wait
• BAD
• BAD
• BAD
10. Futures
• Represent a concurrent computation
• In functional languages, they are... Monads!
val f1 = Future {
"Hello" + "World"
}
val f2 = f1 map {
x x.length
}
11. Futures as Monads
val f1 = ask(actor1, msg1)
val f2 = ask(actor2, msg2)
val f3 = for {
a ← f1.mapTo[Int]
b ← f2.mapTo[Int]
c ← ask(actor3, (a + b)).mapTo[Int]
} yield c
val r = Await.result(f3,1).asInstanceOf[Int]
12. Failure management
• Let it crash
• Supervisor knows an exception is thrown
• Respawns crashed actor
• Simple as that!
• caveat: actor mailbox?
13. Language support
• Erlang, it all started here
• Scala /Akka
•D
• Dart
• Libraries for most other languages