0

How can I broadcast a message to all actors that are watching a particular actor?

For context, suppose I have a AuctionActor (which is potentially a remote actor) that is being watched by a large number of AuctionParticipantActor types. I would like the AuctionActor to broadcast various messages to AuctionParicipantActor types.

One possibility would be for the AuctionActor to keep a collection of all participant ActorRef instances and then loop over this collection when ever a message needs to be sent to all participants. This seems inefficient and I am hoping for a better solution...

davidrpugh
  • 4,363
  • 5
  • 32
  • 46

1 Answers1

1

If you don't want to go with PubSub as mentioned by Diego Martinoia, I would suggest using Routers with BroadcastingLogic. This goes in the direction you mentioned with the collection of ActorRefs, but uses Akka functionality to achieve it being more efficient than just iterating over a collection in your AuctionActor.

From Akka Docs

Routers are designed to be extremely efficient at receiving messages and passing them quickly on to routees.

A normal actor can be used for routing messages, but an actor’s single-threaded processing can become a bottleneck. Routers can achieve much higher throughput with an optimization to the usual message-processing pipeline that allows concurrent routing.

In your case it could look like this:

class AuctionActor extends Actor {
  var router = Router(BroadcastRoutingLogic(), Vector[ActorRefRoutee]())

  def receive = {
    case AddParticipant(ref) =>
      router = router.addRoutee(ref)
    case RemoveParticipant(ref) =>
      router = router.removeRoutee(ref)
    case update: ImportantUpdate =>
      router.route(update, self)
  }
}
Community
  • 1
  • 1
thwiegan
  • 2,163
  • 10
  • 18
  • Does it matter if the `ActorRef` is to a local actor or a remote actor? I think not... – davidrpugh Jun 20 '17 at 11:41
  • That's a good question. I would expect it to be location transparent, but I think it shouldn't be hard to test. You can give it a try, I will do so as well, if I get to it. Would be great if you can give an update. Here seems to be info to remote routers: http://doc.akka.io/docs/akka/current/scala/routing.html#remote-deployed-routees But that looks like it is used to create the routees on remote systems, where as in your case the routees already exist. – thwiegan Jun 20 '17 at 11:47
  • @davidrpugh Tested it, works with remote routees without changes to the code. – thwiegan Jun 20 '17 at 12:05