Immutability is golden

Time and again, we have talked of making data structures immutable. We can pass them around without two threads changing the shared state (that is, data structure) at the same time. Immutability makes up for less moving parts, and hence the reasoning about such systems is simpler.

The issue here is when two (or more) threads update a shared object, a race condition is said to happen. Refer to http://stackoverflow.com/questions/34510/what-is-a-race-condition to know more about races.

If we make the objects immutable, race conditions are not possible, as no thread can update it.

To make a mutable instance immutable, we could wrap it up. However, we should not leak any references out. Here is an example Java snippet that illustrates ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.