13.8. Monitoring the Death of an Actor with watch
Problem
You want an actor to be notified when another actor dies.
Solution
Use the watch
method of an
actor’s context
object to declare
that the actor should be notified when an actor it’s monitoring is
stopped.
In the following code snippet, the Parent
actor creates an actor instance named
kenny
, and then declares that it
wants to “watch” kenny
:
class
Parent
extends
Actor
{
val
kenny
=
context
.
actorOf
(
Props
[
Kenny
],
name
=
"Kenny"
)
context
.
watch
(
kenny
)
// more code here ...
(Technically, kenny
is an
ActorRef
instance, but it’s simpler
to say “actor.”)
If kenny
is killed or stopped,
the Parent
actor is sent a Terminated(kenny)
message. This complete
example demonstrates the approach:
package
actortests.deathwatch
import
akka.actor._
class
Kenny
extends
Actor
{
def
receive
=
{
case
_
=>
println
(
"Kenny received a message"
)
}
}
class
Parent
extends
Actor
{
// start Kenny as a child, then keep an eye on it
val
kenny
=
context
.
actorOf
(
Props
[
Kenny
],
name
=
"Kenny"
)
context
.
watch
(
kenny
)
def
receive
=
{
case
Terminated
(
kenny
)
=>
println
(
"OMG, they killed Kenny"
)
case
_
=>
println
(
"Parent received a message"
)
}
}
object
DeathWatchTest
extends
App
{
// create the ActorSystem instance
val
system
=
ActorSystem
(
"DeathWatchTest"
)
// create the Parent that will create Kenny
val
parent
=
system
.
actorOf
(
Props
[
Parent
],
name
=
"Parent"
)
// lookup kenny, then kill it
val
kenny
=
system
.
actorSelection
(
"/user/Parent/Kenny"
)
kenny
!
PoisonPill
Thread
.
sleep
(
5000 ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.