scalaakkaakka-typedakka-dispatcher

Make Akka guardian actor use custom dispatcher


I have defined a custom dispatcher in application.conf like this:

my-special-dispatcher {
  type = Dispatcher
  executor = "thread-pool-executor"
  thread-pool-executor {
    fixed-pool-size = 1
  }
  throughput = 1
}

The documentation says to create an actor using a custom dispatcher like this:

context
  .spawn(
    yourBehavior, 
    "DispatcherFromConfig", 
    DispatcherSelector.fromConfig("your-dispatcher")
  )

However, I want to use this custom dispatcher for the guardian actor, which is not created via context.spawn.

I currently create my actor system and guardian actor like this:

implicit val myActorSystem: ActorSystem[MyGuardianActor.Request] = {
  ActorSystem[MyGuardianActor.Request](
    MyGuardianActor(), 
    name = "MyGuardianActorSingleton"
  )

How would I modify this to use my custom dispatcher called "my-special-dispatcher"?

Note: I only want to use the custom dispatcher for the guardian actor. All other actors in the system should use the default dispatcher.


Solution

  • You have the ActorSystem class which is what you get when you use the apply method from the ActorSystem companion object. In your case, you are using the one that only receives the user guardian actor and the name of the actor system

    def apply[T](
      guardianBehavior: Behavior[T], 
      name: String
    ): ActorSystem[T]
    

    The factory method that lets you set a dispatcher for the guardian actor is this one

    def apply[T](
      guardianBehavior: Behavior[T], 
      name: String, 
      config: Config, 
      guardianProps: Props
    ): ActorSystem[T]
    

    As you can see, the last param lets you set the dispatcher like you can do when you spawn childs. Doing something like the following example should work for you

    val dispatcherSelector = DispatcherSelector.fromConfig("my-special-dispatcher")
    
    ActorSystem[MyGuardianActor.Request](
      guardianBehavior = MyGuardianActor(), 
      name = "MyGuardianActorSingleton",
      config = ConfigFactory.load(),
      guardianProps = dispatcherSelector
    )