我经常发现自己使用的是“主要”角色,该角色为子任务创建了许多子角色。当子任务完成时,主要演员也应该停下来。因此,当观看context.children.isEmpty
时,我会观看儿童演员并停止主要演员。
我经常使用这种模式,但是因为我从未读过它。 我不确定这是个好主意还是演员失败有问题...?
我已经读过Shutdown Patterns in Akka 2,但是在Java中这种方法似乎比我的解决方案更复杂?
这是我的具有两个子任务的主要演员的伪代码:
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());
}
}
// ...
}
(我必须使用Java 8 :-(,但是如果您可以提供其他解决方案,我也很高兴阅读Scala代码)
最佳答案
因此context().children().isEmpty()
似乎可以正常工作。
但是,在调试我的Akka应用程序时,我发现了这种方法的另一个问题:Terminated
消息何时到达MainActor
中不是确定性的:有时示例中的Terminated
之前是SubTask1Response
消息!
现在,我更改了代码,以自己计算正在运行的子代数,并在MainActor
收到结果响应SubTask[1,2]Response
时减少数字。
=>所以我不会推荐我的原始模式。