Akka Actor library - a toolkit for building highly concurrent, distributed, and resilient message-driven applications for Java and Scala using the Actor Model.
npx @tessl/cli install tessl/maven-com-typesafe-akka--akka-actor_2-13@2.8.0Akka Actor is a foundational library that implements the Actor Model for building highly concurrent, distributed, and fault-tolerant applications on the JVM. It provides lightweight actors that process messages asynchronously, enabling developers to write highly scalable systems that can handle millions of actors per GB of heap memory. The library includes actor lifecycle management, supervision strategies for fault tolerance, location transparency for distributed computing, and comprehensive routing capabilities.
libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.8.8"import akka.actor.{ActorSystem, Actor, ActorRef, Props}
import akka.pattern.ask
import akka.util.TimeoutFor Java API:
import akka.actor.ActorSystem;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.AbstractActor;import akka.actor.{ActorSystem, Actor, ActorRef, Props}
// Define an actor
class HelloActor extends Actor {
def receive = {
case "hello" => println("Hello World!")
case _ => println("Unknown message")
}
}
// Create actor system and actor
val system = ActorSystem("HelloSystem")
val helloActor = system.actorOf(Props[HelloActor](), "helloActor")
// Send messages
helloActor ! "hello"
helloActor ! "goodbye"
// Shutdown system
system.terminate()Akka Actor is built around several key architectural components:
Core actor system creation, configuration, and lifecycle management. The actor system serves as the root container for all actors and provides essential services.
abstract class ActorSystem extends ActorRefFactory with ClassicActorSystemProvider {
def name: String
def settings: Settings
def eventStream: EventStream
def scheduler: Scheduler
def dispatchers: Dispatchers
def terminate(): Future[Terminated]
def whenTerminated: Future[Terminated]
}
object ActorSystem {
def create(): ActorSystem
def create(name: String): ActorSystem
def create(name: String, config: Config): ActorSystem
def apply(): ActorSystem
def apply(name: String): ActorSystem
def apply(name: String, config: Config): ActorSystem
}Actor creation, configuration, and lifecycle management including Props-based instantiation and actor reference handling.
final case class Props(
deploy: Deploy,
clazz: Class[_],
args: immutable.Seq[Any]
) {
def withDispatcher(dispatcher: String): Props
def withMailbox(mailbox: String): Props
}
object Props {
def create[T <: Actor](clazz: Class[T], args: AnyRef*): Props
def apply[T <: Actor: ClassTag](): Props
def apply[T <: Actor: ClassTag](creator: => T): Props
}
trait ActorRefFactory {
def actorOf(props: Props): ActorRef
def actorOf(props: Props, name: String): ActorRef
def actorSelection(path: String): ActorSelection
def actorSelection(path: ActorPath): ActorSelection
}Core message passing primitives, the ask pattern, and various messaging patterns for actor communication.
abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable {
def tell(msg: Any, sender: ActorRef): Unit
def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit
def path: ActorPath
}
// Ask pattern
import akka.pattern.ask
implicit val timeout: Timeout = Timeout(5.seconds)
val future: Future[Any] = actorRef ? messageMessage Passing and Communication
Actor message handling patterns, behavior switching, and message processing capabilities.
trait Actor {
type Receive = PartialFunction[Any, Unit]
def receive: Actor.Receive
def context: ActorContext
def self: ActorRef
def sender(): ActorRef
def become(behavior: Actor.Receive): Unit
def become(behavior: Actor.Receive, discardOld: Boolean): Unit
def unbecome(): Unit
def preStart(): Unit
def postStop(): Unit
def preRestart(reason: Throwable, message: Option[Any]): Unit
def postRestart(reason: Throwable): Unit
}Actor Behavior and Receive Handling
Supervision strategies, fault handling, and the "let it crash" philosophy for building resilient systems.
abstract class SupervisorStrategy {
def decider: Decider
def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit
}
case class OneForOneStrategy(
maxNrOfRetries: Int = -1,
withinTimeRange: Duration = Duration.Inf,
loggingEnabled: Boolean = true
)(decider: Decider) extends SupervisorStrategy
case class AllForOneStrategy(
maxNrOfRetries: Int = -1,
withinTimeRange: Duration = Duration.Inf,
loggingEnabled: Boolean = true
)(decider: Decider) extends SupervisorStrategy
type Decider = PartialFunction[Throwable, Directive]Supervision and Fault Tolerance
Router configurations and strategies for distributing messages across multiple actor instances.
abstract class RouterConfig {
def createRouter(system: ActorSystem): Router
def routerDispatcher: String
def stopRouterWhenAllRouteesRemoved: Boolean
}
abstract class Pool extends RouterConfig {
def nrOfInstances: Int
def resizer: Option[Resizer]
def supervisorStrategy: SupervisorStrategy
}
abstract class Group extends RouterConfig {
def paths: immutable.Iterable[String]
def routerDispatcher: String
}Actor Routing and Load Balancing
Event streaming, logging capabilities, and event bus functionality for system-wide communication.
class EventStream extends ActorEventBus with LookupClassification {
def subscribe(subscriber: ActorRef, channel: Class[_]): Boolean
def unsubscribe(subscriber: ActorRef, channel: Class[_]): Boolean
def unsubscribe(subscriber: ActorRef): Unit
def publish(event: AnyRef): Unit
}
trait LoggingAdapter {
def error(message: String): Unit
def error(cause: Throwable, message: String): Unit
def warning(message: String): Unit
def info(message: String): Unit
def debug(message: String): Unit
}
trait ActorLogging { this: Actor =>
val log: LoggingAdapter
}TCP, UDP, and DNS operations for network communication and I/O management.
object IO {
def apply(key: ExtensionKey[_ <: Extension])(implicit system: ActorSystem): ActorRef
}
object Tcp {
final case class Connect(
remoteAddress: InetSocketAddress,
localAddress: Option[InetSocketAddress] = None,
options: immutable.Traversable[SocketOption] = Nil,
timeout: Option[FiniteDuration] = None,
pullMode: Boolean = false
) extends Command
final case class Connected(
remoteAddress: InetSocketAddress,
localAddress: InetSocketAddress
) extends Event
final case class Received(data: ByteString) extends Event
case object Close extends Command
case object Closed extends Event
}Utility classes, extension system, and helper functions for common operations.
final case class Timeout(duration: FiniteDuration) {
def *(factor: Double): Timeout
def +(other: Timeout): Timeout
def min(other: Timeout): Timeout
def max(other: Timeout): Timeout
}
object Timeout {
implicit def durationToTimeout(duration: FiniteDuration): Timeout
}
class ByteString extends IndexedSeq[Byte] with IndexedSeqOptimized[Byte, ByteString] {
def ++(that: ByteString): ByteString
def take(n: Int): ByteString
def drop(n: Int): ByteString
def slice(from: Int, until: Int): ByteString
def utf8String: String
def decodeString(charset: Charset): String
}// Root types
sealed abstract class NotUsed
case object NotUsed extends NotUsed
sealed abstract class Done
case object Done extends Done
// Actor path types
trait ActorPath {
def address: Address
def name: String
def parent: ActorPath
def root: RootActorPath
def toString: String
}
final case class Address(
protocol: String,
system: String,
host: Option[String] = None,
port: Option[Int] = None
) {
def hasGlobalScope: Boolean
def hasLocalScope: Boolean
}
// Message types
trait AutoReceivedMessage
trait PossiblyHarmful
trait NotInfluenceReceiveTimeout
trait DeadLetterSuppressioncase object PoisonPill extends AutoReceivedMessage with PossiblyHarmful
case object Kill extends AutoReceivedMessage with PossiblyHarmful
final case class Identify(messageId: Any) extends AutoReceivedMessage with NotInfluenceReceiveTimeout
final case class ActorIdentity(correlationId: Any, ref: Option[ActorRef])
final case class Terminated(actor: ActorRef)(
val existenceConfirmed: Boolean,
val addressTerminated: Boolean
) extends AutoReceivedMessage with PossiblyHarmful
case object ReceiveTimeout extends NotInfluenceReceiveTimeoutobject Status {
final case class Success(status: Any)
final case class Failure(cause: Throwable)
}
final case class UnhandledMessage(message: Any, sender: ActorRef, recipient: ActorRef)
// Exception types
class AkkaException(message: String, cause: Throwable) extends RuntimeException(message, cause)
class ConfigurationException(message: String, cause: Throwable) extends AkkaException(message, cause)
final case class IllegalActorStateException(message: String) extends AkkaException(message)
final case class ActorKilledException(message: String) extends AkkaException(message)
final case class InvalidActorNameException(message: String) extends AkkaException(message)