Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get existing or create new akka actor

Tags:

java

akka

actor

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.

like image 475
Hako Avatar asked Apr 28 '13 21:04

Hako


People also ask

How do I create a new actor in Akka?

In Akka you can't create an instance of an Actor using the new keyword. Instead, you create Actor instances using a factory spawn methods. Spawn does not return an actor instance, but a reference, akka. actor.

Can Akka actors stop other actors?

In Akka, you can stop Actors by invoking the stop() method of either ActorContext or ActorSystem class. ActorContext is used to stop child actor and ActorSystem is used to stop top level Actor.

Can an Akka actor stop itself?

An actor can stop itself by returning. Behaviors. stopped as the next behavior. A child actor can be forced to stop after it finishes processing its current message by using the stop method of the ActorContext from the parent actor.


2 Answers

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.

like image 177
Roland Kuhn Avatar answered Oct 12 '22 10:10

Roland Kuhn


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.

like image 39
cmbaxter Avatar answered Oct 12 '22 10:10

cmbaxter