我正在尝试使用ActorFor获取现有的ActorRef,或者如果它不存在则创建一个新的ActorRef。我有以下代码,但它似乎没有按预期工作。 .isTerminated()始终为true。
I'm trying to get an existing ActorRef with ActorFor or create a new one if it does not exists. I have the following code but it doesn't seem to work as expected. .isTerminated() is always true.
ActorSystem system = ActorSystem.create("System"); ActorRef subscriberCandidate = system.actorFor("akka://System/user/"+name); if (subscriberCandidate.isTerminated()) { ActorRef subscriber = system.actorOf(new Props(new UntypedActorFactory() { public UntypedActor create() { return new Sub(name,link); } }), name); System.out.println(subscriber.path().toString() + " created"); } else System.out.println("already exists");我在这里缺少什么?提前致谢。
What am I missing here? Thanks in advance.
推荐答案获取或创建只能由父执行指定的actor,因为只有父级才能创建该actor,如果它不存在,并且只有父级可以一致地这样做(即没有竞争条件)。在演员中你可以做
Get-or-create can only be performed by the parent of the designated actor, since only that parent can create the actor if it does not exist, and only the parent can do so consistently (i.e. without race conditions). Within an actor you can do
// assuming a String name like "fred" or "barney", i.e. without "/" final Option<ActorRef> child = child(name); if (child.isDefined()) return child.get(); else return getContext().actorOf(..., name);不要在顶层执行此操作(即使用 system.actorOf ),因为那时你无法确定谁在申请创建中获胜并且依赖用户监护人并不是一个好的监督策略。
Do not do this at the top-level (i.e. using system.actorOf), because then you cannot be sure who "wins" in requesting creation and also relying on the user guardian is not good a good supervision strategy.
更多推荐
获得现有或创建新的akka演员
发布评论