or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

actor-system.mdactors-props.mdfsm.mdindex.mdmessaging-references.mdpatterns-utilities.mdscheduling-timers.mdsupervision.md

index.mddocs/

0

# Akka Actor

1

2

Akka 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.

3

4

## Package Information

5

6

- **Package Name**: akka-actor

7

- **Package Type**: maven

8

- **Language**: Scala (with Java interop)

9

- **Group ID**: com.typesafe.akka

10

- **Artifact ID**: akka-actor_2.11

11

- **Version**: 2.5.32

12

- **Installation**: `libraryDependencies += "com.typesafe.akka" %% "akka-actor" % "2.5.32"`

13

14

## Core Imports

15

16

```scala

17

import akka.actor._

18

import akka.pattern.ask

19

import akka.util.Timeout

20

import scala.concurrent.duration._

21

```

22

23

For Java:

24

```java

25

import akka.actor.*;

26

import akka.pattern.Patterns;

27

import akka.util.Timeout;

28

import java.time.Duration;

29

```

30

31

## Basic Usage

32

33

```scala

34

import akka.actor._

35

import scala.concurrent.duration._

36

37

// Define an actor

38

class HelloActor extends Actor {

39

def receive = {

40

case "hello" => sender() ! "Hello back!"

41

case _ => println("Unknown message")

42

}

43

}

44

45

// Create actor system and actors

46

val system = ActorSystem("HelloSystem")

47

val helloActor = system.actorOf(Props[HelloActor], "helloActor")

48

49

// Send messages

50

helloActor ! "hello"

51

52

// Shutdown

53

system.terminate()

54

```

55

56

## Architecture

57

58

Akka Actor is built around several key concepts:

59

60

- **Actor Model**: Lightweight, isolated computation units that communicate via asynchronous message passing

61

- **Actor System**: Runtime environment that manages actor lifecycle, message dispatching, and system resources

62

- **Supervision**: Hierarchical fault tolerance with configurable error handling strategies

63

- **Location Transparency**: ActorRef abstraction enables seamless local/remote actor communication

64

- **Message Dispatching**: Pluggable dispatcher system for customizing threading and mailbox behavior

65

- **Extensions**: Modular system for adding functionality like logging, serialization, and patterns

66

67

## Capabilities

68

69

### Core Actor System

70

71

Foundation for creating and managing actors, with system-wide configuration and lifecycle management.

72

73

```scala { .api }

74

abstract class ActorSystem extends ActorRefFactory with ClassicActorSystemProvider {

75

def actorOf(props: Props): ActorRef

76

def actorOf(props: Props, name: String): ActorRef

77

def actorSelection(path: String): ActorSelection

78

def stop(actor: ActorRef): Unit

79

def terminate(): Future[Terminated]

80

def scheduler: Scheduler

81

def dispatcher: ExecutionContextExecutor

82

def eventStream: EventStream

83

def deadLetters: ActorRef

84

def logConfiguration(): Unit

85

def /(name: String): ActorPath

86

def /(name: Iterable[String]): ActorPath

87

88

// Java API helpers

89

def child(child: String): ActorPath = /(child)

90

def descendant(names: java.lang.Iterable[String]): ActorPath

91

def getEventStream: EventStream = eventStream

92

def getScheduler: Scheduler = scheduler

93

def getDispatcher: ExecutionContextExecutor = dispatcher

94

}

95

96

object ActorSystem {

97

// System constants

98

val Version: String = akka.Version.current

99

val EnvHome: Option[String]

100

val SystemHome: Option[String]

101

val GlobalHome: Option[String]

102

103

// Scala API

104

def create(): ActorSystem

105

def create(name: String): ActorSystem

106

def create(name: String, config: Config): ActorSystem

107

def apply(name: String, setup: ActorSystemSetup): ActorSystem

108

def apply(name: String, bootstrapSetup: BootstrapSetup): ActorSystem

109

def apply(name: String, config: Option[Config], classLoader: Option[ClassLoader], defaultExecutionContext: Option[ExecutionContext]): ActorSystem

110

111

// Java API

112

def create(name: String, setups: ActorSystemSetup): ActorSystem

113

def create(name: String, bootstrapSetup: BootstrapSetup): ActorSystem

114

}

115

```

116

117

[Actor System](./actor-system.md)

118

119

### Actor Creation and Props

120

121

Type-safe actor creation with configuration for deployment, dispatching, and mailbox settings.

122

123

```scala { .api }

124

abstract class Actor {

125

def receive: Receive

126

implicit val context: ActorContext

127

implicit final val self: ActorRef

128

final def sender(): ActorRef

129

def preStart(): Unit

130

def postStop(): Unit

131

def supervisorStrategy: SupervisorStrategy

132

}

133

134

class Props private (

135

val deploy: Deploy,

136

val clazz: Class[_],

137

val args: immutable.Seq[Any]

138

) {

139

def withDispatcher(dispatcher: String): Props

140

def withMailbox(mailbox: String): Props

141

}

142

143

object Props {

144

def apply[T <: Actor: ClassTag]: Props

145

def apply(creator: => Actor): Props

146

def create(actorClass: Class[_ <: Actor]): Props

147

}

148

```

149

150

[Actors and Props](./actors-props.md)

151

152

### Message Passing and References

153

154

Immutable actor references with location-transparent message passing and actor selection capabilities.

155

156

```scala { .api }

157

abstract class ActorRef extends java.lang.Comparable[ActorRef] {

158

def !(message: Any)(implicit sender: ActorRef): Unit

159

def tell(msg: Any, sender: ActorRef): Unit

160

def forward(message: Any)(implicit context: ActorContext): Unit

161

def path: ActorPath

162

}

163

164

abstract class ActorSelection {

165

def !(msg: Any)(implicit sender: ActorRef): Unit

166

def tell(msg: Any, sender: ActorRef): Unit

167

def resolveOne(timeout: Timeout): Future[ActorRef]

168

}

169

170

trait ActorContext extends ActorRefFactory {

171

def actorOf(props: Props): ActorRef

172

def stop(actor: ActorRef): Unit

173

def watch(actor: ActorRef): ActorRef

174

def unwatch(actor: ActorRef): ActorRef

175

def become(behavior: Receive): Unit

176

def unbecome(): Unit

177

def children: Iterable[ActorRef]

178

def sender(): ActorRef

179

def self: ActorRef

180

def parent: ActorRef

181

}

182

```

183

184

[Messaging and References](./messaging-references.md)

185

186

### Supervision and Fault Tolerance

187

188

Hierarchical supervision strategies with configurable error handling for building resilient systems.

189

190

```scala { .api }

191

abstract class SupervisorStrategy {

192

def decider: Decider

193

def handleChildTerminated(

194

context: ActorContext,

195

child: ActorRef,

196

children: Iterable[ActorRef]

197

): Unit

198

}

199

200

class OneForOneStrategy(

201

maxNrOfRetries: Int = -1,

202

withinTimeRange: Duration = Duration.Inf,

203

loggingEnabled: Boolean = true

204

)(decider: Decider) extends SupervisorStrategy

205

206

class AllForOneStrategy(

207

maxNrOfRetries: Int = -1,

208

withinTimeRange: Duration = Duration.Inf,

209

loggingEnabled: Boolean = true

210

)(decider: Decider) extends SupervisorStrategy

211

212

// Supervision directives

213

sealed trait Directive

214

case object Resume extends Directive

215

case object Restart extends Directive

216

case object Stop extends Directive

217

case object Escalate extends Directive

218

```

219

220

[Supervision](./supervision.md)

221

222

223

### Patterns and Utilities

224

225

Common actor patterns including ask, circuit breaker, and graceful stop, plus essential utilities.

226

227

```scala { .api }

228

// Ask pattern

229

object AskSupport {

230

implicit class Askable(val actorRef: ActorRef) extends AnyVal {

231

def ask(message: Any)(implicit timeout: Timeout): Future[Any]

232

def ?(message: Any)(implicit timeout: Timeout): Future[Any]

233

}

234

}

235

236

// Circuit breaker

237

class CircuitBreaker(

238

scheduler: Scheduler,

239

maxFailures: Int,

240

callTimeout: Duration,

241

resetTimeout: Duration

242

) {

243

def withCircuitBreaker[T](body: => Future[T]): Future[T]

244

def onOpen(callback: => Unit): CircuitBreaker

245

def onClose(callback: => Unit): CircuitBreaker

246

def onHalfOpen(callback: => Unit): CircuitBreaker

247

}

248

249

// Timeout utility

250

case class Timeout(duration: Duration) {

251

def apply(length: Long, unit: TimeUnit): Timeout

252

}

253

```

254

255

[Patterns and Utilities](./patterns-utilities.md)

256

257

258

### Finite State Machines

259

260

Type-safe finite state machine implementation with state data, transitions, and timer management.

261

262

```scala { .api }

263

trait FSM[S, D] extends Actor {

264

def startWith(stateName: S, stateData: D): Unit

265

def when(stateName: S, stateTimeout: Duration = null)(

266

stateFunction: StateFunction

267

): Unit

268

def goto(nextStateName: S): State

269

def stay(): State

270

def stop(): State

271

def stop(reason: Reason): State

272

def setTimer(name: String, msg: Any, timeout: Duration): Unit

273

def cancelTimer(name: String): Unit

274

def initialize(): Unit

275

}

276

277

type StateFunction = PartialFunction[Event, State]

278

279

case class Event(event: Any, stateData: D)

280

281

case class State(

282

stateName: S,

283

stateData: D,

284

timeout: Option[Duration] = None,

285

stopReason: Option[Reason] = None,

286

replies: List[Any] = Nil

287

)

288

```

289

290

[Finite State Machines](./fsm.md)

291

292

### Scheduling and Timers

293

294

Task scheduling for delayed and periodic execution with cancellation support.

295

296

```scala { .api }

297

trait Scheduler {

298

def schedule(

299

initialDelay: Duration,

300

interval: Duration,

301

receiver: ActorRef,

302

message: Any

303

)(implicit executor: ExecutionContext): Cancellable

304

305

def scheduleOnce(

306

delay: Duration,

307

receiver: ActorRef,

308

message: Any

309

)(implicit executor: ExecutionContext): Cancellable

310

311

def schedule(

312

initialDelay: Duration,

313

interval: Duration,

314

runnable: Runnable

315

)(implicit executor: ExecutionContext): Cancellable

316

}

317

318

trait Cancellable {

319

def cancel(): Boolean

320

def isCancelled: Boolean

321

}

322

323

trait Timers { this: Actor =>

324

def timers: TimerScheduler

325

}

326

327

trait TimerScheduler {

328

def startSingleTimer(key: Any, msg: Any, delay: Duration): Unit

329

def startTimerWithFixedDelay(key: Any, msg: Any, delay: Duration): Unit

330

def startTimerAtFixedRate(key: Any, msg: Any, interval: Duration): Unit

331

def cancel(key: Any): Unit

332

def cancelAll(): Unit

333

def isTimerActive(key: Any): Boolean

334

}

335

```

336

337

[Scheduling and Timers](./scheduling-timers.md)