Search code examples
javamultithreadingconcurrencyakkaactor

Finding the state of all child actors in akka


Within a supervisor -> child actor model where 10 children are created and work is evenly split between all children via RoundRobinRoutingLogic. Some of the actors are programmed to stop after some duration of time. Eventually, I would like to see the state of all my child actors (whether they are alive or not). But I'm not able to see any documentation for this within ActorRef.

Here is part of my Supervisor class:

    Router router;
{
    counter = 0;
    List<Routee> routees = new ArrayList<Routee>();
    for (int i = 0; i < 10; i++) {
        ActorRef r = getContext().actorOf(Props.create(Children.class));
        getContext().watch(r);
        routees.add(new ActorRefRoutee(r));
    }
    router = new Router(new RoundRobinRoutingLogic(), routees);
}

Here is the condition within the child actor which causes them to stop:

if (/*some condition*/) {
   getContext().parent().tell(new Response(startTime, messages, Status.SUCCESS), getContext().parent());
   getContext().stop(getSelf());
}

Which is the correct API within the akka toolkit I can use to print the status of all the child actors within my Supervisor class?


Solution

  • There are a couple ways.

    First, I see that you watch your routees from the supervisor, this is because you have to remove routees from the router when they terminate. Watching an actor means that the watcher (supervisor in your case) will get a Terminated(actorRef) message when a child terminates. You could use this to maintain your own list of active routees (you should already be updating the router when receiving such a message). And because you should already be updating the router, you can always query its routees using router.getRoutees()

    Second, the ActorContext offers the getChildren() method which you could use to enumerate the currently alive routees. You can also use the getChild(name) to check for the status of a specific routee by name, but of course you would have to set a name for those when creating them...

    Third, you can make your own protocol where the supervisor could broadcast a custom message to all routees, and have them reply with another message of yours. The disadvantage of this method is that you have to introduce some kind of timeout mechanism because you will never know how many routees are receiving your message, and as such how may answers to expect.

    I'm stopping here because I think that unless you have more precise requirements, I wouldn't go for anything else than the first solution above... why reinvent the wheel?