What happens when two threads are trying to generate a new shared state?
Let's be clear about what I understand your question to be:
You have some mutable variable of immutable state. Let's use an int for simplicity:
int x = 42;
Then you want two threads to both try to increment x
by 1.
Then you get to synchronize them. Immutability provides little value here.
All immutability guarantees is that the variable you're reading from isn't in some half-way state when read. Since x
is atomic, this doesn't make much sense. Any read you do will get the whole value.
But since you're mutating the variable x
, you need synchronization even though the value is immutable. Each thread is making 2 atomic operations:
y = read x;
write x with y+1;
If both threads read before write, then both threads will see x
, not x+1
. So you need to synchronize things
But what if x
was a pair?
Pair x = {2,4};
Then having immutable Pairs will guarantee that both values are changed at the same time.
But the threads have 4 atomic operations with mutablemutable Pairs:
y = read x.x;
write x.x with y+1;
y = read x.y;
write x.y with y+1;
Every one of them can be interrupted depending on the concurrency of the threads. With immutable Pairs, it forces you to do something like this:
tmp = x;
y = new Pair(tmp.x+1, tmp.y+1);
x = y;
You still need synchronization, because you have the mutable variable x
, but the reference copy to tmp
is atomic. Since tmp
is local, and you know it's not being modified, it doesn't need synchronized even though you're doing two different operations (to read tmp.x
and tmp.y
).
If you think about how objects are used, most of the time, you just want some snapshot and do some operations on it. If you weren't updating x
above, you wouldn't need synchronization. The copy to tmp
will happen automatically when you pass x
into some function.
But since you were asking specifically about updating a mutable reference, you don't get the immutability benefits. If the reference was also read only, then there would be no need to synchronize anything since nothing can change.