Life-cycle hooks
Akka lets us specify code that runs in response to specific events in an actor's life, through life-cycle hooks. Akka defines the following hooks:
preStart()
: This runs after the actor's constructor has finished but before it starts processing messages. This is useful to run initialization code that depends on the actor being fully constructed.postStop()
: This runs when the actor dies after it has stopped processing messages. This is useful to run cleanup code before terminating the actor.preRestart(reason: Throwable, message: Option[Any])
: This is called just after an actor receives an order to restart. ThepreRestart
method has access to the exception that was thrown and to the offending message, allowing for corrective action. The default behavior ofpreRestart
is to stop each child and then callpostStop
.postRestart(reason:Throwable)
: This is called after an actor has restarted. The default behavior is to callpreStart()
.
Let's use system hooks to persist the state...