DJ180 DJ180 - 1 month ago 26
Java Question

Akka: Sharing state across actor instances

My

MyProcessingActor
actor will be routed using a
ConsistentHashingRouter
on an entity ID, such that there may be multiple instances of this actor in process at any one time (across multiple threads)

The actor uses a map to perform some calculation logic. Therefore, 2 different actor instances could be reading and writing to this map at the same time.

Sharing a map across these actor instances seems like a blatant violation of the actor model, even if it is a Java
ConcurrentHashMap
.

What are the best options for dealing with this kind of problem? I didn't see it addressed in the Akka documentation, unless I missed this.

I can see 2 options:


  1. a single instance of a
    MyMapManagerActor
    that will manage reading/writing to this map. If this is single threaded though then effectively
    MyProcessingActor
    would be singlethreaded as well

  2. use of the Akka STM - I do not see this though in the latest version of the project



What other recommended approaches are there?

Answer Source

Unfortunately, this seems to be a quite difficult thing to do in Akka. Creating an actor to manage access to a map proves quite cumbersome, and STM doesn't seem to be supported in the latest versions.

Therefore, the solution here was to choose the key for the ConsistentHashingRouter carefully such that there would never be any race conditions when reading from and writing to a map. The map in question is a ConcurrentHashMap