Immutable Objects – How Changing Them Works

immutability

I have seen examples where even though the object is immutable there are situations in which we need to update some fields and as I understand it, the object is passed to a constructor which makes a copy with updated values but the original is not changed. Fine, but what if two threads want to do this? Do we not run into synchronization problems if they both are changing the same field? And how if now there are new objects made (rather than a changed original) do multiple threads know that the values of fields have changed?

I have seen many examples of how to make an immutable class but it is not clear to me how updating attributes works in a multithreaded environment, how synchronization is not required and as I mentioned above, how to determine what object now represents the current state.

Here is an article in which changing an immutable object is discussed: https://jlordiales.me/2012/12/24/the-ins-and-outs-of-immutability/

Best Answer

Fine, but what if two threads want to do this?

Then one thread makes one change (and gets one version of the object) and another thread makes another change (and gets a different, independent version of the object).

Do we not run into synchronization problems if they both are changing the same field?

Nope, because each thread gets their own copy of the object.

And how if now there are new objects made (rather than a changed original) do multiple threads know that the values of fields have changed?

They don't. That's the point.

how to determine what object now represents the current state.

And that's the gotcha. Immutability works great when things are values, or when things really are independent. But if you have an object that represents a single record - say from a database - then changes need to be merged back into that single record. That can be last in wins. That can be some manner of versioning/timestamping. There's lots of options with various tradeoffs.

But the key bit is that synchronization only needs to happen at that last step where the changes are merged and actually take effect on the single source of truth.