In my previous job (at TIM Media) we used Akka for our RTB system. Lots of actors, lots of messages and a lot of a mess (that’s what you get in RTB systems).
When the system got bigger and bigger with new features and new message types, we came across a situation that we need to prioritize the messages.
Well at that point creating a switch case or if-else like below, will not work nicely. Plus, we had the prioritized mailbox in a shared common package, so if we wanted to add a new type of message, we would need to update all the projects that use this common package - hell no!
The Solution
In our solution, we thought it will be easier just to add an interface to messages that we want to prioritize and all the rest will be with MEDIUM priority.
We created an interface called PrioritizedMessage and 4 more inner interfaces for the priority types.
The 100 fix diff between each priority number, is to allow flexibility between them. If we’ll want to create a new message type that is not High and not Urgent, but it’s something in between,
we will just implement the getPriority method and return a number between 100 to 200, that simple.
Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface,
a simple implement PrioritizedMessage.Urgent will work without having the compiler to scream on you to implement the getPriority method.
That’s leave us with a simple and clean UnboundedStablePriorityMailbox that will use the PrioritizedMessage interface to determine the priority.
PoisonPill / Kill Messages
Once Prioritized Mailbox is configured, the PoisonPill and Kill message types are also been prioritized.
In the example above, the default priority of those types is PrioritizedMessage.HIGH, and by passing in the configuration the priority, one can configure a different priority for those types.
Another Way - Annotation
Instead of using an interface PrioritizedMessage with 4 inner interfaces, a single annotation with a single priority method can be used.
and with a little change in the PrioritizedGenerator class:
hell, you can use even both methods… crazy!!!
The Scala Way
Early this year (2019), I’ve started a new job, and their main language is Scala. This why I’ve decided to try to rewrite this Prioritized Mailbox the “Scala way” (hopefully).