If I have an actor that sends messages to another actor, should I be obtaining a reference to that actor (e.g.
context.actorSelection(somePath)) every time I want to send a message to it or can I do it once when my actor is initialized and then reuse the
Best How To :
I think a distinction needs to be made between an actor failing and being restarted by it's supervisor and an actor being explicitly stopped. If you had an
ActorRef that you had obtained in some way or another (looked it up and resolved it via
ActorSelection or just happened to have it from when it was created) and the underlying actor instance fails and is restarted by its supervisor, then that
ActorRef will still work just fine. Even though the actor technically stops during the fail and restart (
postStop will be called), it's name is never released and any refs that referred to it will still be valid.
Now, if you explicitly stopped that actor, and then later started up a new one with the same name (and thus same path),
ActorRefs that referred to it pre stoping will not work. The actor instance that they referred to was stopped and thus these refs are invalid even though later a new instance was started with the same name and thus same path.
Lastly, you can use
ActorSelections to get around the issue described in the above paragraph. If you keep the result of
.actorSelection as an
ActorSelection and do not resolve it into a single
ActorRef, then you will continue to be able to send messages through it (
ActorSelection supports tell/
!) and to an actor represented by it even if the first instance is initially stopped and a new instance for the same name is started later.