Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Akka: actor current mailbox size or number of messages awaiting processing

Tags:

scala

akka

I am trying to find out number of pending queue items which awaiting to be processed by the actor.

I am sure there must be a method to which you can refer to from actor context or from context.system.mailboxes etc

Here is code example:

class SomeActor extends Actor {
  override def receive = {

    case ScanExisting => {
      val queueSize = context.system.mailboxes... size ??
}
like image 793
Pavel Avatar asked Dec 01 '17 21:12

Pavel


1 Answers

Such a method existed in Akka 1.x but was removed in Akka 2.0. Roland Kuhn wrote a detailed blog post (derived from this discussion on the Akka User List) explaining the rationale behind this decision. Here is an excerpt that outlines some problems with querying an actor's mailbox size:

  • it takes O(n) time to get some size answer from a concurrent queue, i.e. querying hurts when you will feel the pain the most (it might even take several seconds in case of durable mailboxes at the “wrong moment”)

  • the answer is not correct, i.e. it does not need to match the real size at either the beginning or the end of processing this request

  • making it “more correct” involves book-keeping which severely limits scalability

  • and even then the number might have changed completely by the time you receive it in your code (e.g. your thread is scheduled out for 100ms and you get 100.000 new messages during that time).

Read the entire post, then reconsider your reason for obtaining the actor's mailbox size. If you still want it:

In case you cannot do without, it is quite easy to write your own mailbox implementation, building on the traits in the akka.dispatch package and inserting book-keeping code into enqueue() and dequeue(). Then you could either use down-casting (evil) or keep track of your mailboxes in an akka.actor.Extension (recommended) to access the stats from within your actor and do whatever is necessary.

But wait: did I mention that it might even be easier to tag latency-critical (but not too high frequency) messages with timestamps and react on the age of a message when processing it?

So, in summary: while there still is a way to get the mailbox size, you will probably never actually need it.

If you want the actor mailbox size for monitoring purposes, look into Lightbend Telemetry or Kamon. Also, Patrik Nordwall wrote a gist that logs the mailbox size when it exceeds a configured limit.

like image 126
Jeffrey Chung Avatar answered Oct 14 '22 00:10

Jeffrey Chung