Search code examples
playframeworkakka

Akka and getting an ActorRef of a Singleton object


What is the (best) way to get an ActorRef for a Singleton Actor

This is the code I use:

   ActorRef instance = system.actorOf(Props.create(ContactServer.class, encoding, this));
    instance.tell(new AbstractMap.SimpleImmutableEntry<>(device, actionJson), ActorRef.noSender());

The problem I am having is that the Actor never closes, so I end up with a whole lot of actors:

akka://application/user/$e
akka://application/user/$f
akka://application/user/$g
akka://application/user/$h
akka://application/user/$i

However, while I could close the Actor with "getContext().stop(getSelf())", it seems to make more sense to use it as a Singleton as there are no states saved in the Actor. But how to I get a reference to this Actor without creating new ones all the time?


Solution

  • To get the reference of an existing actor, you may either:

    1. Look up an actor by concrete path, see https://doc.akka.io/docs/akka/2.5/general/addressing.html#looking-up-actors-by-concrete-path.
    2. Simply pass the ActorRef around after it is initialized in the actor system.

    In the system I'm currently working on, the 2nd approach works well because it is simple.