There are situations when you want your actor to process some particular messages first, and then move on to others. This means you want to give priority to some messages over others.
For such scenarios, Akka has comes up with priority mailbox, which lets you prioritize messages.
To step through this recipe, we need to import our Hello-Akka
project in IDE-like IntelliJ Idea. Prerequisites are the same as those in previous recipes.
- Create a Scala file named
PriorityMailBox.scala
in packagecomi.packt.chapter1
. - Create an actor called
MyPriorityActor
as follows:
class MyPriorityActor extends Actor { def receive: PartialFunction[Any, Unit] = { // Int Messages case x: Int => println(x) // String Messages case x: String => println(x) // Long messages case x: Long => println(x) // other messages case x => println(x) } }
- To prioritize the messages, create a priority mailbox as follows:
class MyPriorityActorMailbox(settings: ActorSystem.Settings, config: Config) extends UnboundedPriorityMailbox ( // Create a new PriorityGenerator, lower prio means more important PriorityGenerator { // Int Messages case x: Int => 1 // String Messages case x: String => 0 // Long messages case x: Long => 2 // other messages case _ => 3 })
- Add this configuration to
application.conf
:
prio-dispatcher { mailbox-type = "com.packt.chapter1..MyPriorityActorMailbox" }
- Create an application,
PriorityMailBoxApp
, as shown in the following code:
object PriorityMailBoxApp extends App { val actorSystem = ActorSystem("HelloAkka") val myPriorityActor = actorSystem.actorOf(Props[MyPriorityActor].withDispatcher ("prio-dispatcher")) myPriorityActor ! 6.0 myPriorityActor ! 1 myPriorityActor ! 5.0 myPriorityActor ! 3 myPriorityActor ! "Hello" myPriorityActor ! 5 myPriorityActor ! "I am priority actor" myPriorityActor ! "I process string messages first,then integer, long and others" }
- Run the application in IDE or from the console. The following output will be displayed:
Hello I process string messages first,then integer, long and others I am priority actor 1 3 5 6.0 5.0
In step two, we just define an actor which processes Int
, Long
, String
, and other messages.
In step four, we configure a prio-dispatcher
with this MyPriorityActorMailbox
.
In step five, we create an actor which will use the prio-dispatcher
.
In step six, as we can see in the output, the string messages are processed first, because they were given highest priority.