How to create a priority based mailbox for an akka actor


There are some situations when you want an actor to process certain messages first and then other ones. So, I am going to demonstrate how to create a priority based mailbox for an actor.

Suppose we have an actor.


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)
 }

}

Now we want to process our messages in order like (string, Int , Long , other messages).

So what we need to do is to just write a priority based mailbox as below.

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
 })

Here zero denotes highest priority.

After that add this configuration to application.conf.

prio-dispatcher {
 mailbox-type = "com.knoldus.MyPriorityActorMailbox"

}

At the time of actor creation specify the dispatcher class as below.


val system = ActorSystem("priority", ConfigFactory.load)
val myPriorityActor = system.actorOf(Props[MyPriorityActor].withDispatcher("prio-dispatcher"))

Suppose you send below messages to actor, in such a case string messages would be picked up first.


 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"

You can find the sample code here in github.

How to run the code.

After cloning the repo, go to the console and do sbt run in the project directory, it will show following output in console.

priority actor output

About Piyush Mishra

Software Consutant
This entry was posted in Scala. Bookmark the permalink.

4 Responses to How to create a priority based mailbox for an akka actor

  1. Adrien says:

    Note that using this type of mailbox does not preserve message ordering, which you get with the default mailbox queue. So mixing this with for example data streams using Akka IO leads to pretty funny results.

  2. Hi Adrien
    Thanks for sharing your experience. I will look into this as well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s