Dispatchers

Dependency

Dispatchers are part of core akka, which means that they are part of the akka-actor-typed dependency:

sbt
libraryDependencies += "com.typesafe.akka" %% "akka-actor-typed" % "2.5.16"
Maven
<dependency>
  <groupId>com.typesafe.akka</groupId>
  <artifactId>akka-actor-typed_2.11</artifactId>
  <version>2.5.16</version>
</dependency>
Gradle
dependencies {
  compile group: 'com.typesafe.akka', name: 'akka-actor-typed_2.11', version: '2.5.16'
}

Introduction

An Akka MessageDispatcher is what makes Akka Actors “tick”, it is the engine of the machine so to speak. All MessageDispatcher implementations are also an ExecutionContextExecutor, which means that they can be used to execute arbitrary code, for instance Futures.

Selecting a dispatcher

A default dispatcher is used for all actors that are spawned without specifying a custom dispatcher. This is suitable for all actors that don’t block. Blocking in actors needs to be carefully managed, more details here.

To select a dispatcher use DispatcherSelector to create a Props instance for spawning your actor:

Scala
import akka.actor.typed.DispatcherSelector

ctx.spawn(yourBehavior, "DefaultDispatcher")
ctx.spawn(yourBehavior, "ExplicitDefaultDispatcher", DispatcherSelector.default())
ctx.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking())
ctx.spawn(yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher"))
Full source at GitHub
Java
ctx.spawn(yourBehavior, "DefaultDispatcher");
ctx.spawn(yourBehavior, "ExplicitDefaultDispatcher", DispatcherSelector.defaultDispatcher());
ctx.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking());
ctx.spawn(yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher"));
Full source at GitHub

DispatcherSelector has two convenience methods to look up the default dispatcher and a dispatcher you can use to execute actors that block e.g. a legacy database API that does not support FutureCompletionStages.

The final example shows how to load a custom dispatcher from configuration and replies on this being in your application.conf:

Scala
your-dispatcher {
  type = Dispatcher
  executor = "thread-pool-executor"
  thread-pool-executor {
    fixed-pool-size = 32
  }
  throughput = 1
}
Full source at GitHub
Java
your-dispatcher {
  type = Dispatcher
  executor = "thread-pool-executor"
  thread-pool-executor {
    fixed-pool-size = 32
  }
  throughput = 1
}
Full source at GitHub

For full details on how to configure custom dispatchers see the untyped docs.

Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.