It is obvious that an actor has to be shut down gracefully after it has processed all the messages or on application shutdown.
Stopping an actor
Getting ready
To step through this recipe, we need import the Hello-Akka project in an IDE like IntelliJ Idea. Prerequisites are the same as those in previous recipes.
How to do it...
- Create a file, Shutdown.scala, in package com.packt.chapter1.
- Add the following imports to the top of file:
import akka.actor.{PoisonPill, Props, ActorSystem, Actor}
- Create a case object, Stop, as the message:
case object Stop
- Define an actor, ShutdownActor, as follows:
class ShutdownActor extends Actor {
override def receive: Receive = {
case msg:String => println(s"$msg")
case Stop => context.stop(self)
}
}
- There are two ways we can stop the actor:
- Using PoisonPill
- Using context.self(actorRef)
Create an actor and send it a message as shown in the following code:
object ShutdownApp extends App{
val actorSystem = ActorSystem("HelloAkka")
val shutdownActor1 =
actorSystem.actorOf(Props[ShutdownActor],
"shutdownActor1")
shutdownActor1 ! "hello"
shutdownActor1 ! PoisonPill
shutdownActor1 ! "Are you there?"
val shutdownActor2 =
actorSystem.actorOf(Props[ShutdownActor],
"shutdownActor2")
shutdownActor2 ! "hello"
shutdownActor2 ! Stop
shutdownActor2 ! "Are you there?"
}
- Run the preceding application, and you will get the following output:
hello
hello
[INFO] [05/22/2016 20:39:53.137] [HelloAkka-akka.actor.default-
dispatcher-4] [akka://HelloAkka/user/shutdownActor1] Message
[java.lang.String] from Actor[akka://HelloAkka/deadLetters] to
Actor[akka://HelloAkka/user/shutdownActor1#417818231] was not
delivered. [1] dead letters encountered.
[INFO] [05/22/2016 20:39:53.138] [HelloAkka-
akka.actor.default-dispatcher-4]
[akka://HelloAkka/user/shutdownActor2] Message
[java.lang.String] from Actor[akka://HelloAkka/deadLetters]
to Actor[akka://HelloAkka/user/shutdownActor2#788021817] was
not delivered. [2] dead letters encountered.
How it works...
In step three, we create a Stop message. Upon receiving this message, the actor will stop using context.stop(self).
In step four, we define an actor which handles the Stop message.
In step five, we create two actors of the same class, shutdownActor1 and shutdownActor2. We shut down shutdownActor1 using PoisonPill and shutdownActor2 using context.stop(self).
PoisonPill and context.stop(self) are the two ways to kill an actor. PoisonPill is the inbuilt message that is handled after all the messages that were already queued in the mailbox.
Context.stop is basically used for an ordered shutdown of actors when you want the child actors to stop first, then the parent actor, followed by the ActorSystem to stop top-level actors.