How to Stop an Actor... the Right Way
10 minutes to readStopping an actor is a routine operation that developers often find confusing. This is because each actor is like a micro process, and all interaction with an actor is asynchronous. So shutting down an actor is more complex than stopping entities in procedural code.
In this post, I’m going to review one of the common questions that I’ve heard lately:
How do I stop an actor?!
The Ways of Stopping an Actor
In short, there are three ways to stop an actor:
Stop()
the actor: stops the actor immediately after it finishes processing the current message.Kill
the actor: this throws anActorKilledException
which will be logged and handled. The actor will stop immediately after it finishes processing the current message.- Send the actor a
PoisonPill
: the actor will finish processing the messages currently in its mailbox, and thenStop
.
Now let’s go over each in detail.
1) The Default: Stop()
an Actor
This is the go-to method to stop an actor, and should be your default approach.
What Happens When I Stop()
an Actor?
This is the sequence of events when you Stop()
an actor:
- Actor receives the
Stop
message and suspends the actor’sMailbox
. - Actor tells all its children to
Stop
.Stop
messages propagate down the hierarchy below the actor. - Actor waits for all children to stop.
- Actor calls
PostStop
lifecycle hook method for resource cleanup. - Actor shuts down.
The point of this sequence is to make sure that an actor—and any hierarchy beneath it—have a clean shut down.
How Do I Use Stop()
?
You Stop()
an actor...