简体   繁体   中英

Akka: Stop actor after child actors are finished

I often find myself using a "main" actor that creates a number of child actors for sub-tasks. When the sub-tasks are finished, the main actor should also stop himself. So I watch the child actors and stop the main actor when context.children.isEmpty .

I often use this pattern, but as I never read about this. I am unsure, if this is a good idea or if there are problems with failing actors...?

I have read about Shutdown Patterns in Akka 2 , but this approach seems to be more complicated in Java than my solution?

Here is my pseudo code for a main actor with two subtasks:

class MainActor extends AbstractActor {

    public MainActor() {
        receive(ReceiveBuilder
                .match(SubTask1Response.class, this::handleSubTask1)
                .match(SubTask2Response.class, this::handleSubTask2)
                .match(Terminated.class, x -> checkFinished())
                .build());
    }

    @Override
    public void preStart() throws Exception {
        context().watch(context().actorOf(SubTask1Worker.props(), "subTask1"));
        context().watch(context().actorOf(SubTask2Worker.props(), "subTask2"));
    }

    private void checkFinished() {
        if(context().children().isEmpty()) {
            context().stop(self());
        }
    }

    // ...
}

(I must use Java 8 :-(, but I am also happy to read Scala code if you can provide me another solution)

So context().children().isEmpty() seems to work as expected.

But while debugging my Akka application I found another problem with this approach: It is not deterministic when the Terminated message arrives in the MainActor : Sometimes there is the Terminated message before the SubTask1Response from the example!

I have changed now my code to count the running children myself and decrement the number whenever the MainActor receives a result response SubTask[1,2]Response .

=> So I wouldn't recommend my original pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM