Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merely stop child actors upon a parent's restart?

I have an Akka parent actor with several children. When the parent actor is restarted, I need it to simply stop its children, rather than stopping and re-creating or restarting them. (A child would be created manually later, if it's needed.) Is there a way to do this? Perhaps by overriding the parent's preRestart method in some way?

like image 214
Lasf Avatar asked Oct 20 '22 04:10

Lasf


1 Answers

By default Actor disposes of it's children on restart. Here is the Actor.preRestart code:

  /**
   * User overridable callback: '''By default it disposes of all children and then calls `postStop()`.'''
   * @param reason the Throwable that caused the restart to happen
   * @param message optionally the current message the actor processed when failing, if applicable
   * <p/>
   * Is called on a crashed Actor right BEFORE it is restarted to allow clean
   * up of resources before Actor is terminated.
   */
  @throws(classOf[Exception]) // when changing this you MUST also change UntypedActorDocTest
  //#lifecycle-hooks
  def preRestart(reason: Throwable, message: Option[Any]): Unit = {
    context.children foreach { child ⇒
      context.unwatch(child)
      context.stop(child)
    }
    postStop()
  }

As you can see parent will stop and unwatch its children. You can override it like this to make an actor keep it's children alive:

override def preRestart(reason: Throwable, message: Option[Any]): Unit = ()

So for your purposes you don't need to override preRestart and you'll get desired behavior. You can look at other callbacks if you want to have more custom behavior like starting children on start but not on restart event.

like image 135
yǝsʞǝla Avatar answered Nov 01 '22 13:11

yǝsʞǝla