Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preStart hook: a message to the actor itself

Tags:

scala

akka

Let's say I override the preStart hook and send a message to self:

Class SomeActor extends Actor {

  override def preStart(): Unit = {
    self ! SomeMessage
  }

  ...

}

Can I expect that SomeMessage will be the first message in the queue?

like image 606
tokarev Avatar asked May 02 '13 12:05

tokarev


1 Answers

No, since actor creation happens asynchronously someone might have enqueued a message before the constructor or preStart actually run. If you need to ensure processing of this message before any other then you’ll need to use become and stash:

self ! SomeMessage

def receive = initial

def initial: Receive = {
  case SomeMessage =>
    // do stuff
    unstashAll()
    context become initialized
  case _ => stash()
}

def initialized: Receive = {
  // your normal behavior
}

You’ll need to mix in the akka.actor.Stash trait and configure this actor to use a DequeBasedMailbox.

like image 103
Roland Kuhn Avatar answered Oct 21 '22 07:10

Roland Kuhn