获得现有或创建新的akka​​演员 [英] Get existing or create new akka actor

查看:194
本文介绍了获得现有或创建新的akka​​演员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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​​演员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆