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

4 thoughts on “How to create a priority based mailbox for an akka actor

  1. 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.

Leave a Reply

%d bloggers like this: