How to deal with long initialization of an Akka child actor?

后端 未结 3 879
醉酒成梦
醉酒成梦 2021-02-02 15:36

I have an actor which creates a child actor to perform some lengthy computations.

The problem is that the initialization of the child actor takes a few seconds and all

3条回答
  •  面向向阳花
    2021-02-02 16:32

    Don't initialize the tagger in the constructor, but in the preStart hook, this way the messages will be collected in the message box and delivered, when the actor is ready.

    edit:

    You should do the same for the actor creation in your ParentActor class, because you would have the same problem, if the ChildActor would respond, before the ParentActor is initialized.

    edit2:

    I created a simple example, but I was not able to reproduce your problems. Following code works perfectly fine:

    import akka.actor._
    
    case class Tag(x: String)
    
    class ChildActor extends Actor {
      type Tagger = String => String
      var tagger: Tagger = _
    
      override def preStart() = {
        tagger = (x: String) => x+"@tagged" // this takes a few seconds to complete
        Thread.sleep(2000) // simulate time taken to initialize Tagger
      }
    
      def receive = {
        case Tag(text) => sender ! tagger(text)
        case "hello" => println("Hello")
        case _ => println("Unknown message")
      }
    }
    
    class ParentActor extends Actor {
      var child: ActorRef = _
    
      override def preStart() = {
        child = context.actorOf(Props[ChildActor], name = "childactor")
    
        // When I add
        // Thread.sleep(5000)
        // here messages are processed without problems
    
        // wihout hardcoding the 5 seconds waiting 
        // the below two messages seem to get lost
        child ! "hello"
        child ! Tag("This is my sample text")
      }
    
      def receive = {
        case x => println(x)
      }
    }
    
    object Main extends App {
    
      val system = ActorSystem("MySystem")
    
      system.actorOf(Props[ParentActor])
    }
    

    Output is:

    [info] Running Main
    Hello
    This is my sample text@tagged
    

提交回复
热议问题