I have a class that is read heavy with low contention on writes. I'd like 
to be able to access a piece of shared mutable state outside of Actors. The 
state itself (AnnouncementRegistry) is immutable. Since it is a single 
writer, having a shared @volatile var between the actor and the class seems 
to be a good approach, however it also has a code smell to it since I am 
closing over external mutable state and using an anonymous actor. Is there 
a better approach to what I have below?

class DiscoveryClient(config: DiscoveryConfig, singleRequest: HttpRequest => 
Future[HttpResponse])
                     (implicit system: ActorSystem, m: Materializer) {

  @volatile
  private[this] var _registry = AnnouncementRegistry.empty

  def registry = _registry

  private[this] val client = system.actorOf(Props(new Actor with ActorLogging {
    import DiscoveryClient._

    private[this] var subscribers = HashSet.empty[ActorRef]

    private[this] val killswitch =
      ChangeWatcher(config.seeds, singleRequest).to(Sink.foreach(self ! 
RegistryUpdate(_))).run()

    def receive: Receive = uninitialized

    private[this] def uninitialized: Receive = {
      case Subscribe =>
        subscribers += sender
        context.watch(sender)

      case Terminated(ref) =>
        subscribers -= ref

      case m @ RegistryUpdate(newRegistry) =>
        _registry = newRegistry
        context.become(initialized)
        subscribers.foreach(_ ! m)
    }

    private[this] def initialized: Receive = {
      case Subscribe =>
        subscribers += sender
        context.watch(sender)
        sender ! RegistryUpdate(_registry)

      case Terminated(ref) =>
        subscribers -= ref

      case m @ RegistryUpdate(newRegistry) =>
        _registry = newRegistry
        subscribers.foreach(_ ! m)
    }

    override def postStop(): Unit = killswitch.shutdown()
  }), "discovery-client")
}

-- 
>>>>>>>>>>      Read the docs: http://akka.io/docs/
>>>>>>>>>>      Check the FAQ: 
>>>>>>>>>> http://doc.akka.io/docs/akka/current/additional/faq.html
>>>>>>>>>>      Search the archives: https://groups.google.com/group/akka-user
--- 
You received this message because you are subscribed to the Google Groups "Akka 
User List" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/akka-user.
For more options, visit https://groups.google.com/d/optout.

Reply via email to