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.32"
- Maven
<dependencies> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor-typed_2.12</artifactId> <version>2.5.32</version> </dependency> </dependencies>
- Gradle
dependencies { implementation "com.typesafe.akka:akka-actor-typed_2.12:2.5.32" }
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 ExecutionContext
Executor
, 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
-
source
import akka.actor.typed.DispatcherSelector context.spawn(yourBehavior, "DefaultDispatcher") context.spawn(yourBehavior, "ExplicitDefaultDispatcher", DispatcherSelector.default()) context.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking()) context.spawn(yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher"))
- Java
-
source
context.spawn(yourBehavior, "DefaultDispatcher"); context.spawn( yourBehavior, "ExplicitDefaultDispatcher", DispatcherSelector.defaultDispatcher()); context.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking()); context.spawn( yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher"));
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 Future
CompletionStage
s.
The final example shows how to load a custom dispatcher from configuration and replies on this being in your application.conf:
- Scala
-
source
your-dispatcher { type = Dispatcher executor = "thread-pool-executor" thread-pool-executor { fixed-pool-size = 32 } throughput = 1 }
- Java
-
source
your-dispatcher { type = Dispatcher executor = "thread-pool-executor" thread-pool-executor { fixed-pool-size = 32 } throughput = 1 }
For full details on how to configure custom dispatchers see the untyped docs.