Message driven concurrency
The following listing shows our first actor-based program in action. We show a single actor, living in an actor system and we talk to this actor by sending messages. These messages land in the actor's mailbox and each message is processed sequentially, one at a time:
package com.concurrency.book.chapter08 import akka.actor.{Actor, ActorLogging, ActorSystem, Props} class MyActor extends Actor { override def receive: PartialFunction[Any, Unit] = { case s: String => println(s"<${s}>") case i: Int => println(i+1) } } object MyActor extends App { def props() = Props(new MyActor) val actorSystem = ActorSystem("MyActorSystem") val actor = actorSystem.actorOf(MyActor.props(), name = "MyActor") actor ! "Hi" actor ! 34 case class Msg( msgNo: Int) actor ! Msg(3) actor ! 35 actorSystem.terminate() }
We have an actor, named MyActor
, which lives in an actor system named MyActorSystem
. We create the actor and hold its actorReference
in the actor variable...