Skip to content
Scala

Akka Actors (Pekko)

Message-passing concurrency with the actor model.

By EZ4Code Team
actorakkaconcurrency

Code

import akka.actor.{Actor, ActorSystem, Props}

class Counter extends Actor {
  var count = 0
  def receive: Receive = {
    case "inc"  => count += 1
    case "get"  => sender() ! count
    case "reset" => count = 0
  }
}

val system = ActorSystem("my-system")
val counter = system.actorOf(Props[Counter](), "counter")

counter ! "inc"
counter ! "inc"
counter ! "get"
// Use ask pattern for async reply:
// val f = counter ? "get"

Explanation

Actors encapsulate state and communicate via immutable messages, avoiding shared-memory locks. Akka (now Pekko after the license change) is the canonical implementation. Each actor processes one message at a time, making concurrency safe. Use ? (ask) for request-response, ! (tell) for fire-and-forget.

More Scala Snippets