Akka: Get the total number of participants
Is there an easy way to get the total of all live ActorSystems (as of Java8 API)?
It would be useful for me to debug my application: I create Actors in many different places and I want to be sure that they all finish correctly. An account for child actors will help me know if the total will increase or stay roughly the same as I launch the app for several weeks.
source to share
You can create an actor that will send Identify () messages to all actors in the actor system and then count the responses. The caveat is that actors can be created / deleted while these identity messages are being processed, and some actors might be too busy to respond in time. So the number should be considered an approximation, which is probably fine for your purposes. Below is some uncompiled and untested code, but it should give you an idea:
import akka.actor._ import scala.concurrent.duration.FiniteDuration object CounterActor { case class CountRequest(requestId : String, timeout : FiniteDuration) case class FinishCounting(requestId : String, originalSender : ActorRef) case class CountResponse(requestId : String, count : Int) } class CounterActor extends Actor with Timers { import CounterActor._ var counters = Map[String, Int]() def receive = { case CountRequest(requestId, timeout) => counters = counters.updated(requestId, 0) context.actorSelection("/user/*") ! Identify(requestId) timers.startSingleTimer("timeout", FinishCounting(requestId, sender()), timeout) case ActorIdentity(cId, ref) => counters = counters.updated(cId.toString, counters.getOrElse(cId.toString, 0) + 1) ref.foreach { ref => context.actorSelection(ref.path / "*") ! Identify(cId) } case FinishCounting(requestId, originalSender) => originalSender ! CountResponse(requestId, counters.getOrElse(requestId, 0)) } }
source to share
You can recursively call children
on The Guardian actor ( /user:
) and do depth traversal to get the number of your actors. This may not be accurate because some members may be created or deleted during this operation. In steady state conditions, you should get an accurate score.
NOTE. I have not tested this.
source to share