tokarev
tokarev

Reputation: 2625

preStart hook: a message to the actor itself

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?

Upvotes: 13

Views: 3765

Answers (1)

Roland Kuhn
Roland Kuhn

Reputation: 15472

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.

Upvotes: 31

Related Questions