Creating Guardian Actor with SpawnProtocol

I want to create a GuardianActor with the capability of spawning actors. I’m confused how this actor should be created. Currently I’m trying to do something like this →

public class GuardianActor extends AbstractBehavior<SpawnProtocol.Command>{
   
    private GuardianActor(ActorContext<SpawnProtocol.Command> context){
         super(context);
    }
    
    public static Behavior<SpawnProtocol.Command> createRootBehavior() { 
         return Behaviors.setup(context -> { 
                   // some initial tasks
                   return new GuardianActor(context); 
        });

   @Override 
   public Receive<SpawnProtocol.Command> createReceive() {
        return newReceiveBuilder().onMessage(SpawnProtocol.Command.class, this::onSpawnProtocolCommand).build();
   }

   private Behavior<SpawnProtocol.Command> onSpawnProtocolCommand(SpawnProtocol.Command msg) {

   // what do i do here?

   return this;
  }
}

Here antyime a SpawnProtocol.Spawn<> message is sent to the GuardianActor it is intercepted by the method specified in createReceive. However if I simply return SpawnProtocol.create() from the createRootBehavior then the creation of the actor just takes place on its own. What is the correct pattern to follow ?

The SpawnProtocol already is an actor that you can use as guardian without needing to create a class implementing the message handling yourself:

ActorSystem<SpawnProtocol.Command> system = 
  ActorSystem.create(SpawnProtocol.create(), "MySystem");

If you are curious about how that is implemented you can find the sources here, they are written in Scala but you can probably get the gist of it even if you only know Java.

1 Like

Hi Johan,
Thanks for your reply. This makes it quite clear. Since you mention that SpawnProtocol is already an actor that can be used as a guardian, how would I “send” a message to this actor? Is it safe to pass around ActorSystem<SpawnProtocol.Command> system to constructors?

ActorSystem<T> is also the ActorRef<T> of the guardian actor, so you can pass to methods/constructors that does not know that it is the actor system.

1 Like

Hi @AND2797
Maybe you will be also interested to have a look into the library that I created recently: GitHub - dmmax/akka-spawn-protocol: Uses Spawn Protocol to create Akka Actors from outside. It can be applied at any level of actors' hierarchy, it is a kinda extended version of Akka’s spawn protocol that also supports Guice as an extension