Actors

Akka changed to the BSL license in 2022; Apache Pekko is the Apache-2.0 fork with the same API.

36.1 Akka / Apache Pekko Typed

Akka changed to the BSL license in 2022; Apache Pekko is the Apache-2.0 fork with the same API.

Features: supervision strategies (restart/resume/stop), ask pattern, routers, Cluster (sharding, singleton, distributed data), Persistence (event sourcing), HTTP, gRPC, Streams.

import org.apache.pekko.actor.typed.*
import org.apache.pekko.actor.typed.scaladsl.Behaviors

object Counter:
  sealed trait Command
  case object Increment extends Command
  final case class Get(replyTo: ActorRef[Int]) extends Command

  def apply(count: Int = 0): Behavior[Command] = Behaviors.receiveMessage {
    case Increment => Counter(count + 1)
    case Get(replyTo) =>
      replyTo ! count
      Behaviors.same
  }

@main def runActors(): Unit =
  val system = ActorSystem(Counter(), "counter")
  system ! Counter.Increment
  system ! Counter.Increment

36.2 When to use actors

Stateful entities with high concurrency (IoT devices, game sessions), distributed systems with location transparency, event-sourced domains. For request/response services, effect systems are often simpler.