Akka Actor provides the foundational Actor Model implementation for building concurrent, distributed, resilient and elastic applications with supervision hierarchies and location transparency.
npx @tessl/cli install tessl/maven-com-typesafe-akka--akka-actor_2-11@2.5.0Akka Actor is the foundational module of the Akka toolkit, providing a complete Actor Model implementation for building concurrent, distributed, resilient, and elastic applications. It offers high-level abstractions for state management, supervision hierarchies, and location transparency, enabling fault-tolerant systems that scale both up and out.
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.5.32"import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._For Java:
import akka.actor.*;
import akka.pattern.Patterns;
import akka.util.Timeout;
import java.time.Duration;import akka.actor._
import scala.concurrent.duration._
// Define an actor
class HelloActor extends Actor {
def receive = {
case "hello" => sender() ! "Hello back!"
case _ => println("Unknown message")
}
}
// Create actor system and actors
val system = ActorSystem("HelloSystem")
val helloActor = system.actorOf(Props[HelloActor], "helloActor")
// Send messages
helloActor ! "hello"
// Shutdown
system.terminate()Akka Actor is built around several key concepts:
Foundation for creating and managing actors, with system-wide configuration and lifecycle management.
abstract class ActorSystem extends ActorRefFactory with ClassicActorSystemProvider {
def actorOf(props: Props): ActorRef
def actorOf(props: Props, name: String): ActorRef
def actorSelection(path: String): ActorSelection
def stop(actor: ActorRef): Unit
def terminate(): Future[Terminated]
def scheduler: Scheduler
def dispatcher: ExecutionContextExecutor
def eventStream: EventStream
def deadLetters: ActorRef
def logConfiguration(): Unit
def /(name: String): ActorPath
def /(name: Iterable[String]): ActorPath
// Java API helpers
def child(child: String): ActorPath = /(child)
def descendant(names: java.lang.Iterable[String]): ActorPath
def getEventStream: EventStream = eventStream
def getScheduler: Scheduler = scheduler
def getDispatcher: ExecutionContextExecutor = dispatcher
}
object ActorSystem {
// System constants
val Version: String = akka.Version.current
val EnvHome: Option[String]
val SystemHome: Option[String]
val GlobalHome: Option[String]
// Scala API
def create(): ActorSystem
def create(name: String): ActorSystem
def create(name: String, config: Config): ActorSystem
def apply(name: String, setup: ActorSystemSetup): ActorSystem
def apply(name: String, bootstrapSetup: BootstrapSetup): ActorSystem
def apply(name: String, config: Option[Config], classLoader: Option[ClassLoader], defaultExecutionContext: Option[ExecutionContext]): ActorSystem
// Java API
def create(name: String, setups: ActorSystemSetup): ActorSystem
def create(name: String, bootstrapSetup: BootstrapSetup): ActorSystem
}Type-safe actor creation with configuration for deployment, dispatching, and mailbox settings.
abstract class Actor {
def receive: Receive
implicit val context: ActorContext
implicit final val self: ActorRef
final def sender(): ActorRef
def preStart(): Unit
def postStop(): Unit
def supervisorStrategy: SupervisorStrategy
}
class Props private (
val deploy: Deploy,
val clazz: Class[_],
val args: immutable.Seq[Any]
) {
def withDispatcher(dispatcher: String): Props
def withMailbox(mailbox: String): Props
}
object Props {
def apply[T <: Actor: ClassTag]: Props
def apply(creator: => Actor): Props
def create(actorClass: Class[_ <: Actor]): Props
}Immutable actor references with location-transparent message passing and actor selection capabilities.
abstract class ActorRef extends java.lang.Comparable[ActorRef] {
def !(message: Any)(implicit sender: ActorRef): Unit
def tell(msg: Any, sender: ActorRef): Unit
def forward(message: Any)(implicit context: ActorContext): Unit
def path: ActorPath
}
abstract class ActorSelection {
def !(msg: Any)(implicit sender: ActorRef): Unit
def tell(msg: Any, sender: ActorRef): Unit
def resolveOne(timeout: Timeout): Future[ActorRef]
}
trait ActorContext extends ActorRefFactory {
def actorOf(props: Props): ActorRef
def stop(actor: ActorRef): Unit
def watch(actor: ActorRef): ActorRef
def unwatch(actor: ActorRef): ActorRef
def become(behavior: Receive): Unit
def unbecome(): Unit
def children: Iterable[ActorRef]
def sender(): ActorRef
def self: ActorRef
def parent: ActorRef
}Hierarchical supervision strategies with configurable error handling for building resilient systems.
abstract class SupervisorStrategy {
def decider: Decider
def handleChildTerminated(
context: ActorContext,
child: ActorRef,
children: Iterable[ActorRef]
): Unit
}
class OneForOneStrategy(
maxNrOfRetries: Int = -1,
withinTimeRange: Duration = Duration.Inf,
loggingEnabled: Boolean = true
)(decider: Decider) extends SupervisorStrategy
class AllForOneStrategy(
maxNrOfRetries: Int = -1,
withinTimeRange: Duration = Duration.Inf,
loggingEnabled: Boolean = true
)(decider: Decider) extends SupervisorStrategy
// Supervision directives
sealed trait Directive
case object Resume extends Directive
case object Restart extends Directive
case object Stop extends Directive
case object Escalate extends DirectiveCommon actor patterns including ask, circuit breaker, and graceful stop, plus essential utilities.
// Ask pattern
object AskSupport {
implicit class Askable(val actorRef: ActorRef) extends AnyVal {
def ask(message: Any)(implicit timeout: Timeout): Future[Any]
def ?(message: Any)(implicit timeout: Timeout): Future[Any]
}
}
// Circuit breaker
class CircuitBreaker(
scheduler: Scheduler,
maxFailures: Int,
callTimeout: Duration,
resetTimeout: Duration
) {
def withCircuitBreaker[T](body: => Future[T]): Future[T]
def onOpen(callback: => Unit): CircuitBreaker
def onClose(callback: => Unit): CircuitBreaker
def onHalfOpen(callback: => Unit): CircuitBreaker
}
// Timeout utility
case class Timeout(duration: Duration) {
def apply(length: Long, unit: TimeUnit): Timeout
}Type-safe finite state machine implementation with state data, transitions, and timer management.
trait FSM[S, D] extends Actor {
def startWith(stateName: S, stateData: D): Unit
def when(stateName: S, stateTimeout: Duration = null)(
stateFunction: StateFunction
): Unit
def goto(nextStateName: S): State
def stay(): State
def stop(): State
def stop(reason: Reason): State
def setTimer(name: String, msg: Any, timeout: Duration): Unit
def cancelTimer(name: String): Unit
def initialize(): Unit
}
type StateFunction = PartialFunction[Event, State]
case class Event(event: Any, stateData: D)
case class State(
stateName: S,
stateData: D,
timeout: Option[Duration] = None,
stopReason: Option[Reason] = None,
replies: List[Any] = Nil
)Task scheduling for delayed and periodic execution with cancellation support.
trait Scheduler {
def schedule(
initialDelay: Duration,
interval: Duration,
receiver: ActorRef,
message: Any
)(implicit executor: ExecutionContext): Cancellable
def scheduleOnce(
delay: Duration,
receiver: ActorRef,
message: Any
)(implicit executor: ExecutionContext): Cancellable
def schedule(
initialDelay: Duration,
interval: Duration,
runnable: Runnable
)(implicit executor: ExecutionContext): Cancellable
}
trait Cancellable {
def cancel(): Boolean
def isCancelled: Boolean
}
trait Timers { this: Actor =>
def timers: TimerScheduler
}
trait TimerScheduler {
def startSingleTimer(key: Any, msg: Any, delay: Duration): Unit
def startTimerWithFixedDelay(key: Any, msg: Any, delay: Duration): Unit
def startTimerAtFixedRate(key: Any, msg: Any, interval: Duration): Unit
def cancel(key: Any): Unit
def cancelAll(): Unit
def isTimerActive(key: Any): Boolean
}