简体   繁体   中英

Actor good practice?

I have an akka actor system running using scala. Now I need to configure multiple devices in parallel so I have a Manager actor that manages all those configuration tasks. To actually configure them he will spawn a Worker actor per configuration so that they run concurrently or parallel. Now the Worker actor doesn't really need to receive messages from the manager during the configuration he only needs to do his thing and then report that he has finished back to the Manager .

Now the question is do I pass the instructions and the ActorRef of the Manager in the constructor of the Worker or do I create it and then send it a message like Do(action: => Unit) and it will then reply to sender upon completion? Is there a convention how to do this or is one considered good practice?

EDIT : As Vladimir Matveev reminded me the reference to the Manager is not a problem as it is already known through the hierarchy in context.parent . That leaves only the question of how to pass the work to the Worker .

You are right, the work should be passed to the worker via messages. As this is the most safe way to communicate with an actor. It also enables you to use a dispatcher in front of the actor to split assigned work over multiple workers.

To make things clear, here is a short example:

import akka.actor.Actor
import akka.actor.Props

case class Start()
case class Finished()
case class Do(action: () => Unit)

class Manager extends Actor {

  override def preStart() =
    self ! Start()

  def receive = {
    case Start() =>
      val workers = context.actorOf(
        Props[Worker].withRouter(RoundRobinRouter(nrOfInstances = 5)))
      context.system.scheduler.schedule(5 seconds, 5 seconds, workers, Do(() => 1 * 1))

    case Finished() =>
      println("A worker finished work.")
  }
}

class Worker extends Actor {
  def receive = {
    case Do(f) =>
      f()
      sender ! Finished()
  }
}

After the manager gets started, it will create 5 workers and send them something to work on every 5 seconds. The Workers will execute the work and report back when they are finished. You can either use sender (always report to the issuer of the work) or context.parent (always report to the manager) to report finished work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM