Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exactly does akka need immutable messages

or put another way: are there proper uses of mutable messages?

The use case I am facing is that I want to process objects which basically are of type

Map<String,List<String>>

The typical processing an actor would do is to read or write some of the fields of the map. A condensed example is (leaving out null-tests etc.)

  map.get("somekey").add("new value");

My hunch is that keeping this immutable in Scala would be trivial by using the respective collection types. In Java it would require to go for some additional class library.

But: reading the Akka docs, I find that sending a message introduces a happens-before relation between the last access of the sender and the first access of the receiving actor. So if the map is not immutable, nevertheless the sender should see all data.

Suppose I can make sure that the sender will never touch the map again once it is send, is there any other problem to expect with regards to threaded data access to this map?

like image 986
Harald Avatar asked Dec 25 '22 09:12

Harald


2 Answers

The OP’s interpretation of the happens-before rule is correct: the “actor send rule” means that sending M to actor A happens-before processing M by A (this is what “the same” refers to).

To answer the main question: as long as only at most one actor can “own” the mutable map at any given point in time, this will work, and depending on the circumstances this may well be the most efficient solution to the problem. Guaranteeing the single-ownership will require a bit of discipline, though, which offsets the runtime advantage by a maintenance cost.

Although the original question leaves out the actual vehicle for transporting the Map I would like to reinforce Randall’s point that messages between actors should never be JDK types, since those lack semantic meaning. The Map should in this case be contained within a clearly named custom message type.

like image 182
Roland Kuhn Avatar answered Jan 06 '23 14:01

Roland Kuhn


You should be fine if the data is effectively immutable. This is easier to enforce if there data is immutable, however with discipline you can treat the map as effectively immutable after you send it.

like image 45
Peter Lawrey Avatar answered Jan 06 '23 15:01

Peter Lawrey