Get existing or create new akka actor

大城市里の小女人 提交于 2019-11-30 14:14:37

问题


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.


回答1:


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);

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.




回答2:


Change your lookup to be:

system.actorFor("/user/" + name)

You don't need the "akka://System" part if this is a local actor you are looking up. This is assuming that this actor was already started up elsewhere in your code though. If not it won't work.




回答3:


Based on the given code you are calling actorFor to look up a non-existent actor. The actor doesn't exist until actorOf is called.



来源:https://stackoverflow.com/questions/16268333/get-existing-or-create-new-akka-actor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!