Question

I have a List (e.g. the output of a database query) variable, which I use to create actors (they could be many and they are varied). I use the following code (in TestedActor preStart()), the actor qualified name is from the List variable as an example):

Class<?> classobject = Class.forName("com.java.anything.actor.MyActor"); //create class from name string
ActorRef actref = getContext().actorOf(Props.create(classobject), actorname); //creation

the code was tested:

@Test
public void testPreStart() throws Exception {
    final Props props = Props.create(TestedActor.class);
    final TestActorRef<TestedActor > ref = TestActorRef.create(system, props, "testA");
    @SuppressWarnings("unused")
    final TestedActor actor = ref.underlyingActor();
}

EDIT : it is working fine (contrary to the previous post, where I have seen a timeout error, it turned out as an unrelated alarm).

I have googled some posts related to this issue (e.g. suggesting the usage of newInstance), however I am still confused as these were superseded by mentioning it as a bad pattern. So, I am looking for a solution in java, which is also safe from the akka point of view (or the confirmation of the above pattern).

Was it helpful?

Solution

Maybe if you would write us why you need to create those actors this way it would help to find the solution.

Actually most people will tell you that using reflection is not the best idea. Sometimes it's the only option but you should avoid it.

Maybe this would be a solution for you:

Since actors are really cheap you can create all of them upfront. How many of them do you have?

Now the query could return you a path to the actor, not the class. Select it with actorSelection and send messages to it.

If your actors does a long running job you can use a router or if you want to a Proxy Actor that will spawn other actors as needed. Other option is to create futures from a single actor.

It really depends on the case, because you may need to create multiple execution context's not to starve any of the actors (of futures).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top