How to initialise a scala/akka Actor in an event driven architecture?

350 views Asked by At

I have got long running processes, let's say 2h to 1day. Each process starts its lifecycle with an update message and then continues to listen further concurrent updates. In the update message there is a unique target identifier.

If I want to represent each process with an Actor, how do I initialize the actor? I clearly need to do an atomic look-up/create operation based on the value of the identifier in the update message? How to do I design this with scala/akka?

2

There are 2 answers

0
cmbaxter On BEST ANSWER

Setup a single actor that performs the management of these process actors (say a ProcessManager actor). This actor will support requests to get a process actor for a particular process id. Internally, it will see if that child already exists or not. If it exists, it will respond to the sender with that ref. If not, it will create it and then respond to the sender with that ref. Because this manager actor processes it's mailbox serially (as all actors do), you don't have to worry about race conditions with the lookup/create. A very simplified example of this:

case class GetProcessHandler(processId:Int)

class ProcessManager extends Actor{

  def receive = {
    case GetProcessHandler(id) =>
      val name = s"proc_$id"
      val handler = context.child(name).getOrElse(
        context.actorOf(Props[ProcessHandler], name)
      )
      sender ! handler
  }
}

class ProcessHandler extends Actor{
  def receive = {
    ...
  }
}
0
Soumya Simanta On

You can specify your starting actors in your application.conf. And then your main program you can create/initialize these actors by using your ActorSystem.