Reputation: 31
I am in process an application using Akka. I have a scenario where an actor will fetch certain values from database in an array or a list. The child actors will refer this list but they won't be allowed to modify or update the same.
Is there any way I can share data among the actors?
Upvotes: 1
Views: 254
Reputation: 19527
Simply make the list that the parent actor populates from the database immutable. Then the parent can share this list with the child actors without concern for the pitfalls that come with shared mutable state. The child actors can ask the parent for the list, and the parent can send the list to the children, via message passing. The actors could look something like this:
case object GetFromDb
case object GetList
case object ProcessList
class ParentActor extends Actor {
var fromDb: List[Something] = List()
def receive = {
case GetFromDb =>
// query the database and replace fromDb with a new list
fromDb = // ...
case GetList =>
sender() ! fromDb
}
}
class ChildActor(parent: ActorRef) extends Actor {
def receive = {
case ProcessList =>
// get the list from the parent
parent ! GetList
case fromDb: List[Something] =>
// do something with the list
}
}
In the above example, the actors pass an immutable list as-is, but the list could easily be placed inside a case class, if you prefer. Also note that the child actors take as a constructor argument a reference to the parent actor, but a child could also use context.parent
to obtain a reference to its parent.
Upvotes: 1