Tuesday 10 June 2014

Understanding how Immutable variables really help make your programs thread-safe

I have read some times before that choice of immutable variables over mutable ones is a good idea from the perspective of building thread-safe applications. It's not as if I did not understand this. But, there were some intricacies in the basics that I had trouble recollecting which is why I thought I would write it down here.

Talking about shared memory, data consistency, visibility and synchronization when you have multiple flows of control in your program; it is important to recollect that these are really issues only when the values change. Also, for values to change, you need write operations. So, it is easy to infer that when values do not change, there are no write operations at all. Thus, we need to remember that concurrent/even simultaneous reads by multiple threads of a value that does not ever change is actually not a problem at all!

I asked myself this question recently when I was trying to access an array with multiple threads, each thread accessing a different index of the array (mutually exclusive access). As simple as it is to understand that it is a thread-safe operation, it took me a while to actually be sure that I was doing right.