Problem: Shared mutable variables/state
One solution: Isolated Mutability
Lots of work writing/debugging the “plumbing” rather than application logic
Easy to create deadlock and hard to recover from
Developed in 1986 by Joe Armstrong
Allows you to write at a higher level than jvm concurrency tools
Most of the “plumbing” is taken care of for you – focus on application logic instead
Send them messages, stored in message queue
Share state via message passing
Biggest difference: no shared memory
Only one message is processed at a time from the queue
Client sends messages to actor
Actor has a receive method
Thread pool serves an actor, when message is finished processing, thread is returned to the thread pool
Deadlocks still possible, but you can recover and get the thread back via timeouts
Actor doesn’t always get the same thread, this is abstracted away
Actors only process one message at a time
Scala actors vs akka actors
Provide the full Erlang actor model in Scala
Lightweight/small memory footprint
Lifecycle hooks: preStart, postStop, preRestart, preRestart
Supports supervisors and ActorRegistry
Akka is to become the standard actor framework of Scala
Useful when you have tasks you want to run at the same time but each task must be sequential
No handling locks, etc. – can focus on writing higher level code
Supervisors are responsible for monitoring child Actors and restarting them when necessary
Actors treat reads and writes exactly the same
Readers are not given any more priority than writers (lots of reads will be delayed until reads and writes in front of them are finished)
Deadlock still possible with two way communication
Try to avoid using two-way communication
Pattern: Give actor a message to go do something, when it’s done it sends another actor its answer (rather than blocking waiting for a response)
Need immutable messages to send to actors, if they are both accessing mutable state, we have a problem
Can include as a dependency in your sbt projects
Using g8 template for example
% brew install giter8
% g8 typesafehub/akka-scala-sbt
% cd <dir>
Open PingPong.scala and walk through the code
Ping and Pong are two actors that exchange messages a pre-determined number of times
It’s a good practice to include the messages that an object responds to in Protocol objects
Open the Scala REPL and paste in the object and class definitions
Try to instantiate a Pong instance directly and explain why that is not possible
val pong = new Pong
Run the PingPongTest example and explain how the threads are managed by the default dispatcher
Allows messages to be processed in parallel (mice)
RabbitMQ client integrates AMQP messaging with Akka
Scribe - communicate with persistent datastores with Akka-style messaging