Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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 ??
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...