我经常使用一个“主”actor来创建多个子actor来执行子任务。当子任务完成时,主actor也应该停止。因此,我会监视子actor,并在context.children.isEmpty
时停止主actor。
我经常使用这种模式,但由于从未阅读过相关文献,所以不确定这是否是一个好主意或者是否存在失败的actor问题?
我已经阅读了Akka 2中的关闭模式, 但是相比我的解决方案,这种方法在Java中似乎更加复杂?
以下是我的伪代码,用于具有两个子任务的主actor:
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代码编写,我也很乐意阅读。