Functional Programming – How Immutability Removes the Need for Locks

functional programmingimmutabilitymultithreading

Okay so I read through this:

Does immutability entirely eliminate the need for locks in multi-processor programming?

And this was the main takeaway for me:

Now, what does it get you? Immutability gets you one thing: you can read the immutable object freely, without worrying about its state changing underneath you

But that was only regarding reading.

What happens when two threads are trying to generate a new shared state? Lets say they're both reading some immutable number N, and want to increment it. They can't mutate it directly so the both generate two completely new values at the same time both of which are just N + 1.

How do you reconcile this problem so that the shared state becomes N + 2? Or am I missing something and that's not how it works?

Best Answer

So I think that we need to eliminate the term "shared state" from your question, because shared state is almost diametrically opposed to the notion of using immutability to avoid locking.

In your example, you basically said that both read some value "N" and both create a new object with a value "N+1".

The key is that you wouldn't necessarily save the value "N+1". Rather, you would save the values "N" and "+1" inside both threads 1 and 2. In other words, you would save a reference to the original value you read as well as the modification that you made to it.

Now, the "shared state" should instead be a 3rd thread that reconciles the two (very often this 3rd thread is the thread that originally created the first 2). When reconciling the two "N+1" values, it should see that both started with "N" and both did a modification of "+1". The final result is "N+2".

It is important to recognize that "N+2", when saved, will also be a new immutable object that cannot be changed. It is this lack of this "shared state" that allows you to avoid the need for locks.