0
# Akka Actor
1
2
Akka 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.
3
4
## Package Information
5
6
- **Package Name**: akka-actor_2.13
7
- **Package Type**: maven
8
- **Language**: Scala
9
- **Installation**: `libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.8.8"`
10
11
## Core Imports
12
13
```scala
14
import akka.actor.{ActorSystem, Actor, ActorRef, Props}
15
import akka.pattern.ask
16
import akka.util.Timeout
17
```
18
19
For Java API:
20
21
```java
22
import akka.actor.ActorSystem;
23
import akka.actor.ActorRef;
24
import akka.actor.Props;
25
import akka.actor.AbstractActor;
26
```
27
28
## Basic Usage
29
30
```scala
31
import akka.actor.{ActorSystem, Actor, ActorRef, Props}
32
33
// Define an actor
34
class HelloActor extends Actor {
35
def receive = {
36
case "hello" => println("Hello World!")
37
case _ => println("Unknown message")
38
}
39
}
40
41
// Create actor system and actor
42
val system = ActorSystem("HelloSystem")
43
val helloActor = system.actorOf(Props[HelloActor](), "helloActor")
44
45
// Send messages
46
helloActor ! "hello"
47
helloActor ! "goodbye"
48
49
// Shutdown system
50
system.terminate()
51
```
52
53
## Architecture
54
55
Akka Actor is built around several key architectural components:
56
57
- **Actor System**: The root container that manages actor hierarchies, configuration, and system services
58
- **Actors**: Lightweight computational entities that process messages sequentially and maintain private state
59
- **Actor References**: Location-transparent handles to actors that enable message passing
60
- **Supervision Tree**: Hierarchical fault-tolerance mechanism where parent actors supervise child actors
61
- **Message Dispatching**: Configurable threading and scheduling system for message processing
62
- **Routing System**: Load balancing and message distribution across multiple actor instances
63
64
## Capabilities
65
66
### Actor System Management
67
68
Core actor system creation, configuration, and lifecycle management. The actor system serves as the root container for all actors and provides essential services.
69
70
```scala { .api }
71
abstract class ActorSystem extends ActorRefFactory with ClassicActorSystemProvider {
72
def name: String
73
def settings: Settings
74
def eventStream: EventStream
75
def scheduler: Scheduler
76
def dispatchers: Dispatchers
77
def terminate(): Future[Terminated]
78
def whenTerminated: Future[Terminated]
79
}
80
81
object ActorSystem {
82
def create(): ActorSystem
83
def create(name: String): ActorSystem
84
def create(name: String, config: Config): ActorSystem
85
def apply(): ActorSystem
86
def apply(name: String): ActorSystem
87
def apply(name: String, config: Config): ActorSystem
88
}
89
```
90
91
[Actor System Management](./actor-system.md)
92
93
### Actor Creation and Lifecycle
94
95
Actor creation, configuration, and lifecycle management including Props-based instantiation and actor reference handling.
96
97
```scala { .api }
98
final case class Props(
99
deploy: Deploy,
100
clazz: Class[_],
101
args: immutable.Seq[Any]
102
) {
103
def withDispatcher(dispatcher: String): Props
104
def withMailbox(mailbox: String): Props
105
}
106
107
object Props {
108
def create[T <: Actor](clazz: Class[T], args: AnyRef*): Props
109
def apply[T <: Actor: ClassTag](): Props
110
def apply[T <: Actor: ClassTag](creator: => T): Props
111
}
112
113
trait ActorRefFactory {
114
def actorOf(props: Props): ActorRef
115
def actorOf(props: Props, name: String): ActorRef
116
def actorSelection(path: String): ActorSelection
117
def actorSelection(path: ActorPath): ActorSelection
118
}
119
```
120
121
[Actor Creation and Lifecycle](./actor-lifecycle.md)
122
123
### Message Passing and Communication
124
125
Core message passing primitives, the ask pattern, and various messaging patterns for actor communication.
126
127
```scala { .api }
128
abstract class ActorRef extends java.lang.Comparable[ActorRef] with Serializable {
129
def tell(msg: Any, sender: ActorRef): Unit
130
def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit
131
def path: ActorPath
132
}
133
134
// Ask pattern
135
import akka.pattern.ask
136
137
implicit val timeout: Timeout = Timeout(5.seconds)
138
val future: Future[Any] = actorRef ? message
139
```
140
141
[Message Passing and Communication](./messaging.md)
142
143
### Actor Behavior and Receive Handling
144
145
Actor message handling patterns, behavior switching, and message processing capabilities.
146
147
```scala { .api }
148
trait Actor {
149
type Receive = PartialFunction[Any, Unit]
150
151
def receive: Actor.Receive
152
def context: ActorContext
153
def self: ActorRef
154
def sender(): ActorRef
155
156
def become(behavior: Actor.Receive): Unit
157
def become(behavior: Actor.Receive, discardOld: Boolean): Unit
158
def unbecome(): Unit
159
160
def preStart(): Unit
161
def postStop(): Unit
162
def preRestart(reason: Throwable, message: Option[Any]): Unit
163
def postRestart(reason: Throwable): Unit
164
}
165
```
166
167
[Actor Behavior and Receive Handling](./actor-behavior.md)
168
169
### Supervision and Fault Tolerance
170
171
Supervision strategies, fault handling, and the "let it crash" philosophy for building resilient systems.
172
173
```scala { .api }
174
abstract class SupervisorStrategy {
175
def decider: Decider
176
def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit
177
}
178
179
case class OneForOneStrategy(
180
maxNrOfRetries: Int = -1,
181
withinTimeRange: Duration = Duration.Inf,
182
loggingEnabled: Boolean = true
183
)(decider: Decider) extends SupervisorStrategy
184
185
case class AllForOneStrategy(
186
maxNrOfRetries: Int = -1,
187
withinTimeRange: Duration = Duration.Inf,
188
loggingEnabled: Boolean = true
189
)(decider: Decider) extends SupervisorStrategy
190
191
type Decider = PartialFunction[Throwable, Directive]
192
```
193
194
[Supervision and Fault Tolerance](./supervision.md)
195
196
### Actor Routing and Load Balancing
197
198
Router configurations and strategies for distributing messages across multiple actor instances.
199
200
```scala { .api }
201
abstract class RouterConfig {
202
def createRouter(system: ActorSystem): Router
203
def routerDispatcher: String
204
def stopRouterWhenAllRouteesRemoved: Boolean
205
}
206
207
abstract class Pool extends RouterConfig {
208
def nrOfInstances: Int
209
def resizer: Option[Resizer]
210
def supervisorStrategy: SupervisorStrategy
211
}
212
213
abstract class Group extends RouterConfig {
214
def paths: immutable.Iterable[String]
215
def routerDispatcher: String
216
}
217
```
218
219
[Actor Routing and Load Balancing](./routing.md)
220
221
### Event System and Logging
222
223
Event streaming, logging capabilities, and event bus functionality for system-wide communication.
224
225
```scala { .api }
226
class EventStream extends ActorEventBus with LookupClassification {
227
def subscribe(subscriber: ActorRef, channel: Class[_]): Boolean
228
def unsubscribe(subscriber: ActorRef, channel: Class[_]): Boolean
229
def unsubscribe(subscriber: ActorRef): Unit
230
def publish(event: AnyRef): Unit
231
}
232
233
trait LoggingAdapter {
234
def error(message: String): Unit
235
def error(cause: Throwable, message: String): Unit
236
def warning(message: String): Unit
237
def info(message: String): Unit
238
def debug(message: String): Unit
239
}
240
241
trait ActorLogging { this: Actor =>
242
val log: LoggingAdapter
243
}
244
```
245
246
[Event System and Logging](./events-logging.md)
247
248
### I/O Operations
249
250
TCP, UDP, and DNS operations for network communication and I/O management.
251
252
```scala { .api }
253
object IO {
254
def apply(key: ExtensionKey[_ <: Extension])(implicit system: ActorSystem): ActorRef
255
}
256
257
object Tcp {
258
final case class Connect(
259
remoteAddress: InetSocketAddress,
260
localAddress: Option[InetSocketAddress] = None,
261
options: immutable.Traversable[SocketOption] = Nil,
262
timeout: Option[FiniteDuration] = None,
263
pullMode: Boolean = false
264
) extends Command
265
266
final case class Connected(
267
remoteAddress: InetSocketAddress,
268
localAddress: InetSocketAddress
269
) extends Event
270
271
final case class Received(data: ByteString) extends Event
272
case object Close extends Command
273
case object Closed extends Event
274
}
275
```
276
277
[I/O Operations](./io.md)
278
279
### Utilities and Extensions
280
281
Utility classes, extension system, and helper functions for common operations.
282
283
```scala { .api }
284
final case class Timeout(duration: FiniteDuration) {
285
def *(factor: Double): Timeout
286
def +(other: Timeout): Timeout
287
def min(other: Timeout): Timeout
288
def max(other: Timeout): Timeout
289
}
290
291
object Timeout {
292
implicit def durationToTimeout(duration: FiniteDuration): Timeout
293
}
294
295
class ByteString extends IndexedSeq[Byte] with IndexedSeqOptimized[Byte, ByteString] {
296
def ++(that: ByteString): ByteString
297
def take(n: Int): ByteString
298
def drop(n: Int): ByteString
299
def slice(from: Int, until: Int): ByteString
300
def utf8String: String
301
def decodeString(charset: Charset): String
302
}
303
```
304
305
[Utilities and Extensions](./utilities.md)
306
307
## Types
308
309
### Core Types
310
311
```scala { .api }
312
// Root types
313
sealed abstract class NotUsed
314
case object NotUsed extends NotUsed
315
316
sealed abstract class Done
317
case object Done extends Done
318
319
// Actor path types
320
trait ActorPath {
321
def address: Address
322
def name: String
323
def parent: ActorPath
324
def root: RootActorPath
325
def toString: String
326
}
327
328
final case class Address(
329
protocol: String,
330
system: String,
331
host: Option[String] = None,
332
port: Option[Int] = None
333
) {
334
def hasGlobalScope: Boolean
335
def hasLocalScope: Boolean
336
}
337
338
// Message types
339
trait AutoReceivedMessage
340
trait PossiblyHarmful
341
trait NotInfluenceReceiveTimeout
342
trait DeadLetterSuppression
343
```
344
345
### Lifecycle Messages
346
347
```scala { .api }
348
case object PoisonPill extends AutoReceivedMessage with PossiblyHarmful
349
case object Kill extends AutoReceivedMessage with PossiblyHarmful
350
351
final case class Identify(messageId: Any) extends AutoReceivedMessage with NotInfluenceReceiveTimeout
352
final case class ActorIdentity(correlationId: Any, ref: Option[ActorRef])
353
354
final case class Terminated(actor: ActorRef)(
355
val existenceConfirmed: Boolean,
356
val addressTerminated: Boolean
357
) extends AutoReceivedMessage with PossiblyHarmful
358
359
case object ReceiveTimeout extends NotInfluenceReceiveTimeout
360
```
361
362
### Status and Error Types
363
364
```scala { .api }
365
object Status {
366
final case class Success(status: Any)
367
final case class Failure(cause: Throwable)
368
}
369
370
final case class UnhandledMessage(message: Any, sender: ActorRef, recipient: ActorRef)
371
372
// Exception types
373
class AkkaException(message: String, cause: Throwable) extends RuntimeException(message, cause)
374
class ConfigurationException(message: String, cause: Throwable) extends AkkaException(message, cause)
375
final case class IllegalActorStateException(message: String) extends AkkaException(message)
376
final case class ActorKilledException(message: String) extends AkkaException(message)
377
final case class InvalidActorNameException(message: String) extends AkkaException(message)
378
```