I was trying to migrate my code from Akka 2.0 to 2.3. I got several problems.
public synchronized ActorRef getActor(Class<? extends UntypedActor> clsActor, String sID)
{
String sName = clsActor.getName() + "-" + sID;
ActorRef actor = m_actorSystem.actorFor("user/" + sName);
if (actor.isTerminated())
actor = m_actorSystem.actorOf(new Props(clsActor), sName);
return actor;
}
This is a actor dispatcher. If this actor dead or not exist, it would create a new actor.
But in Akka 2.3, isTerminated() is deprecated.
public ActorRef getActor(Class<? extends UntypedActor> clsActor, int id)
{
String sName = clsActor.getName() + "-" + id;
ActorRef actor = m_actorSystem.actorSelection("user/" + sName).anchor();
return actor;
}
I get a actor back, but I don't know whether it is alive, until I send a message out. Surely, it not worked.
How to fix this code?
Thanks.
You could look into using ActorSelection similar to what you have already, but you need to call resolveOne on it which looks it up and returns a Future. You can then evaluate the result.
public ActorRef getActor(Class<? extends UntypedActor> clsActor, int id)
{
String sName = clsActor.getName() + "-" + id;
ActorSelection sel = m_actorSystem.actorSelection("user/" + sName);
Timeout timeout = new Timeout(100, TimeUnit.MILLISECONDS);
Future<ActorRef> fut = sel.resolveOne(timeout);
ActorRef actor= Await.result(fut, timeout.duration());
return actor;
}
If the actor doesn't exist an ActorNotFound
exception will be thrown so you should decide where you want to handle this.
Also, be aware of the blocking nature of the Await.result call.