Search code examples
javaakkaactor

How to create multiple Actors in AKKA by a loop in java?


this is just a learning example, I wan't to create and assign a actor for each element in an array,

ActorSystem system = ActorSystem.create("mySystem");
for(String name:namesArray){
  ActorRef myActor = system.actorOf(Props.create(Actor.class),name);
}

Will this create multiple actor or will it create actor paths that reference to the same actor? if its the latter how do i create multiple actors and assign them a identifier?


Solution

  • That code will:

    • Create an ActorSystem
    • Create an actor for every name in the namesArray (it will throw an InvalidActorNameException if a name appears a second time in the array)

    Note that this code as written promptly forgets the ActorRef for every one of the created actors, meaning that you would not be able to send it a message except by using ActorSelection which is generally not recommended. Going along with this, it's worth noting that the actor will continue running even if there are no ActorRefs for that actor (actors must be explicitly stopped).