Apparently you're using Futures within an actor, since you mention context.dispatcher
and context.system.dispatcher
. Note that these two options are not necessarily the same (but they typically are the same):
context.system.dispatcher
is the default dispatcher.
context.dispatcher
is the dispatcher for a particular actor, which is the same as the default dispatcher unless you set up a custom dispatcher for the actor programmatically or via the configuration.
As for which ExecutionContext
to use with a Future inside an actor, the documentation advises the following:
If the nature of the Future calls invoked by the actor matches or is compatible with the activities of that actor (e.g. all CPU bound and no latency requirements), then it may be easiest to reuse the dispatcher for running the Futures by importing context.dispatcher
.
However, if the Future wraps a blocking operation, then using context.dispatcher
(which, as mentioned, is usually the default dispatcher) could cause the other actors sharing the same dispatcher to starve for threads. In this scenario, use a dedicated dispatcher, which in your actor would like something like this:
implicit val executionContext: ExecutionContext =
context.system.dispatchers.lookup("my-blocking-dispatcher")
my-blocking-dispatcher
would be defined in application.conf
. For example:
my-blocking-dispatcher {
type = Dispatcher
executor = "thread-pool-executor"
thread-pool-executor {
fixed-pool-size = 10
}
throughput = 1
}
Also note that defining a custom dispatcher in the configuration and letting the actor system instantiate it is the preferred approach to setting up a thread pool in Akka. That is, use the above approach instead of using
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
In short, when using Futures within actors, consider using context.dispatcher
in general. However, if you're dealing with blocking or long-running operations with the Futures, then use a dedicated dispatcher to bulkhead or isolate those operations from impacting the rest of the system.