Unable to create an actor using UnTypedActorFactory of akka java api

允我心安 提交于 2019-12-10 10:58:10

问题


I am trying to create an actor with untyped actor factory, compilation happens fine. But while running the application, I get the following error. Am I missing anything in configuration?

Java Code:

MyActor myactor = new MyActor();  //MyActor extends UnTypedActor
ActorSystem system = ActorSystem.create("mynamespace");
ActorRef actor = system.actorOf(new Props(new UntypedActorFactory() {
      public UntypedActor create() {
          return myactor;
      }
  }));

Error during runtime:

Caused by: akka.actor.ActorInitializationException: You cannot create an instance of [com.practice.MyActor] explicitly using the constructor (new). You have to use one of the factory methods to create a new actor. Either use: 'val actor = context.actorOf(Props[MyActor])'
(to create a supervised child actor from within an actor), or 'val actor = system.actorOf(Props(new MyActor(..)))' (to create a top level actor from the ActorSystem)


回答1:


That's because you are creating the instance of MyActor outside the ActorSystem. Create the Actor inside of your factory (that's what it is for ;-) ) and it should be fine.

ActorSystem system = ActorSystem.create("mynamespace");
ActorRef actor = system.actorOf(new Props(new UntypedActorFactory() {
  public UntypedActor create() {
    return new MyActor();
  }
}));

In this case you don't even need a factory, because you have a default constructor. Just pass the class as parameter to the Props:

system.actorOf(new Props(MyActor.class));


来源:https://stackoverflow.com/questions/10735716/unable-to-create-an-actor-using-untypedactorfactory-of-akka-java-api

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