by kubanczyk · 6y ago · 0 comments
If you are spending 100 ms calculating the new version of the immutable structure, you want to make sure that the nearby thread isn't making their own version. You don't want any of the two results silently overwritten. You want the nearby thread be sequential - to wait for you and base on your result.
eg
x = [1,2,3]
Thread1 -> x + [4] => [1,2,3,4]
Thread2 -> x + [5] => [1,2,3,5]
But you were expecting [1,2,3,4,5]
Reality was that you wanted an order to your events, normally enforced by locking, which the immutable vector doesn't seem to help you with; they were both able to update independently, but you actually wanted them to update dependently.
If you try to use immutable datastructures to avoid locking, then how is conflict resolution handled?
I think the answer would be that it doesn't help you avoid locking; either you lock & share a single reference to the latest version of your immutable vector, to enforce ordered events, or you define a resolution strategy separately. The immutability aspect just stops you from not having a resolution strategy -- which would always be incorrect
And if I understand correctly, the ideal scenario for immutable datastructures in concurrent scenarios is when you can define such a merge strategy (and safely give threads their own copy of the datastructure to muddle with, without actually having to copy the entire datastructure)
Again using git as an example, there is the persistent data structure, aka the commit graph, as well as mutable references to commits, aka branches. A change to what commit a branch references needs to be synchronized.
It's great to have git as a mental model in this discussion, really useful.
Having used immutable data structures and concurrency in non-clojure languages, I mostly resort to something like concurrentML for concurrency. Message passing lets you solve situations like that in more elegant ways.
However, to agree with part of your point, an atom being updated with CAS can only ever progress linearly; if you bang 8 threads in a loop trying to update it, you might as well use a lock, because 7/8 of the work is going to be thrown out.
They should only be used for cases where on average one thread or less is working on updating it; anything more, and it needs to be split, the problem rethought, or some mechanism for not throwing out wasted work implemented.
It's not a silver bullet.