import akka.actor._ case class Ping(target: ActorRef) case class Pong(target: ActorRef) case class Zong(target: ActorRef) class Player(private val NUMBER_OF_RALLIES: Int) extends Actor{ private var receivedBallCounter = 0 def receive = { case Ping(targetPlayerRef) => { println("ping") receivedBallCounter += 1 if ( receivedBallCounter < NUMBER_OF_RALLIES ) { targetPlayerRef ! Pong(self) } else { targetPlayerRef ! Pong(self) targetPlayerRef ! PoisonPill } } case Pong(targetPlayerRef) => { println("pong") receivedBallCounter += 1 if ( receivedBallCounter < NUMBER_OF_RALLIES ) { targetPlayerRef ! Ping(self) } else { targetPlayerRef ! PoisonPill } } case _ => { println("Unhandled message") } } } val NUMBER_OF_RALLIES = 5 val actorSystem = ActorSystem("PingPongTraining") val player1 = actorSystem.actorOf(Props(classOf[Player], NUMBER_OF_RALLIES)) val player2 = actorSystem.actorOf(Props(classOf[Player], NUMBER_OF_RALLIES)) player1 ! Zong(player2) player1 ! Ping(player2) player1 ! Zong(player2) actorSystem.shutdown /********************* POISON_PILL ********************* * A PoisonPill message will stop an actor when the message is processed. * A PoisonPill message is queued just like an ordinary message * and will be handled after other messages queued ahead of it in its mailbox. */ /********************* context.stop(self) ********************* * The difference is in which messages get processed before this sequence starts. * In the case of the stop call, the message currently being processed is completed first, * with all others discarded. */ /********************* Console output ********************* * scala> :load 12_1.scala * Loading 12_1.scala... * import akka.actor._ * defined class Ping * defined class Pong * defined class Zong * defined class Player * NUMBER_OF_RALLIES: Int = 5 * actorSystem: akka.actor.ActorSystem = akka://PingPongTraining * player1: akka.actor.ActorRef = Actor[akka://PingPongTraining/user/$a#-1157019602] * player2: akka.actor.ActorRef = Actor[akka://PingPongTraining/user/$b#-546795948] * Unhandled message * ping * pong * ping * pong * ping * pong * ping * pong * ping * pong * [INFO] [01/15/2018 22:07:07.545] [PingPongTraining-akka.actor.default-dispatcher-5] [akka://PingPongTraining/user/$a] Message [$line233.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw$Zong] from Actor[akka://PingPongTraining/deadLetters] to Actor[akka://PingPongTraining/user/$a#-1157019602] was not delivered. [1] dead letters encountered. This logging can be turned off or adjusted with configuration settings 'akka.log-dead-letters' and 'akka.log-dead-letters-during-shutdown'. * */