What is Akka?

A Five-ish Minute Introduction

Created by Todd Ginsberg for CJUG

Who is this guy?

I just moved here from Austin, TX

So come say hi after this!

I've worked with Java for 20 years.

Caveats!

  • This is a quick five minute introduction, so I'm leaving a lot out!
  • All of my experience with Akka is on personal projects.

OK, so what IS Akka?

“Akka is a toolkit and runtime for building highly concurrent, distributed, and resilient message-driven applications on the JVM.”

...and it does this with the Actor Concurrency model.

Thread-based Concurrency

  • Tricky to write/debug.
  • Lends itself to shared state for communication.
  • Errors can lead to states that are unanticipated.
  • Can be tightly coupled and hard to test.

Actor Concurrency

How does this help?

  • State is mutated in one place.
  • Within an actor, there are no race conditions.
  • Easy to reason about what an Actor is doing.
  • Loosely coupled and location independent.
  • Easy to test.
  • Actors take up almost no space - millions in a VM.

Basic Example

Actor:


class CounterActor extends Actor with ActorLogging {
  var counter = 0

  def receive = {
    case Increment =>
      counter += 1
      sender ! CounterState(counter)
    case Decrement =>
      counter -= 1
      sender ! CounterState(counter)
  }
}

Sending a Message:


val actor = system.actorOf(CounterActor.props, "myCounter")
actor ! Increment

Supervision

Let it crash!

  • Each actor has a supervisor (its parent).
  • When an actor fails to handle a message properly, the supevisor can...
    • Resume processing keeping current state
    • Restart the actor from scratch
    • Stop the actor
    • Escalate the failure to its parent

Example Supervisor


override val supervisorStrategy =
  OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
    case _: ArithmeticException      => Resume
    case _: NullPointerException     => Restart
    case _: IllegalArgumentException => Stop
    case _: Exception                => Escalate
  }
(Borrowed from the Akka documentation!)

So What?

  • Separation of actor code from failure handling.
  • Separation of decision making from doing the handling.

Out-of-the-box Patterns

Ask

Used when you want to wait for the answer


val futureAnswer = actor ? Increment
val result = Await.result(futureAnswer, 10 seconds)
println(result)

Routers

Many different strategies supported.

Or write your own!

And Much More!

  • Finite State Machines
  • Event Sourcing (Persistence)
  • Circuit Breaker
  • Clustering and Failover
  • Many options for most components

What Now?

Visit http://akka.io for very comprehensive documentation and examples.

FIN

Thanks!