Saturday 11 July 2015

Watch the Death of an Actor

Use the watch method of an actor’s context object to declare that the actor should be notified when an actor it’s monitoring is stopped.
class Parent extends Actor {
  // start Kenny as a child, then keep an eye on it
  val kenny = context.actorOf(Props[Kenny], name = "Kenny")
  context.watch(kenny)

  def receive = {
    case Terminated(kenny) => println("OMG, they killed Kenny")
    case _ => println("Parent received a message")
  }
}
If kenny is killed or stopped, the Parent actor is sent a Terminated(kenny)message.
Using the watch method lets an actor be notified when another actor is stopped (such as with the PoisonPill message), or if it’s killed with a Kill message orgracefulStop. This can let the watching actor handle the situation, as desired.
An important thing to understand is that if the Kenny actor throws an exception, this doesn’t kill it. Instead it will be restarted.

No comments:

Post a Comment