Here are my knowing about immutable data structures, especially immutable map, correct me if I'm wrong:
- When updating, they don't mutate internal structure but they create a copy version with updated data.
- They are usually implemented by tree-like data structures because copying a tree branch is much more efficient than copying a linear list.
- When there are many threads using them, their states among those threads are not synchronized. Some threads might be using an old version of them but the reading thread doesn't have to wait for the updating thread to finish.
- There is at least a lock is required to synchronize the assignments to a shared variable referencing to the data structure (but in Java assignment is atomic so this is not a problem).
If there are two threads t1
and t2
inserting to an immutable map the same key. Right before t1
done its job and updating the shared reference, t2
starts its job and receives the old version of the map whose key is not inserted yet and continue to insert the same key. Now the final version of the map depends on which thread updating the shared reference last. In both cases, there is an abandoned key-value which is cleaned soon by the garbage collector.
My question is how can I solve the problem when two threads are inserting the same key to an immutable map whose reference is shared among thread? Or using shared reference is wrong in the first place?
Map
by nature