context.stop(self) // to stop itself
System.stop(actorRef) // actor system will stop specified actor
context.stop(actorRef) // stop any other actor from current actor
actorRef ! PoisonPill // get into the mailbox in the end
actorRef ! Kill // get into the mailbox in the end
An actor can stop itself and also it can stop another actor.
A stopped actor is no longer operable.
After the termination of the actor, we can override the postStop() hook, and now it would be available for garbage collection.
Stopping Actor with the API
Both ActorSystem and ActorContext provide a stop method.
Stopping an actor is an asynchronous and recursive operation:
The actor finishes processing the current message if any
Suspends message processing,
Stops its children, and
Waits for their termination confirmations and then terminates itself.
So, stopping an actor automatically stops all its descendants.
Stopping Actor with the PoisonPill and kill
PoisonPill and kill are specially handled messages that get enqueued into the actor’s mailbox and cause the actor to stop when they’re handled.
When an Actor handles a PoisonPill message it simply calls context.stop(self()).
When an actor handles a kill message it throws an ActorKilledException.
Both allow an actor to finish handling all messages placed in their mailbox before the PoisonPill or Kill.
Moreover, these behaviors can’t be overridden by handling the messages yourself, not appropriate when the Actor needs to perform cleanup before shutting down.
Elegant way to stop an actor
If an actor needs to perform certain tasks before stopping it
then it should advertise a dedicated message for that purpose,
handle it as appropriate and stop it after that and stop it after that.