Skip to content

Instantly share code, notes, and snippets.

@daviscale
Created November 21, 2012 13:31
Show Gist options
  • Save daviscale/4124844 to your computer and use it in GitHub Desktop.
Save daviscale/4124844 to your computer and use it in GitHub Desktop.
Akka intro presentation

Actor Based Concurrency

Why actors?

Problem: Shared mutable variables/state

One solution: Isolated Mutability

Threads/Locks
Lots of work writing/debugging the “plumbing” rather than application logic
Easy to create deadlock and hard to recover from

Another Solution: Actors

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

What is an actor?

Run in their own threads

Send them messages, stored in message queue

Only one message is processed at a time from the queue

Akka Actors Basics

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

Pros/Cons

Pros

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

Cons

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

Akka Example

Getting Started

Getting Akka

Can include as a dependency in your sbt projects

Using g8 template for example

% brew install giter8 % g8 typesafehub/akka-scala-sbt % cd <dir>

Ping Pong Example

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

How is Akka Used in 2.0?

Allows messages to be processed in parallel (mice)

RabbitMQ client integrates AMQP messaging with Akka

Scribe - communicate with persistent datastores with Akka-style messaging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment