Yes, Immutable Means Thread Safe. It's that simple.

Plain and simple, IMMUTABLE IS ALWAYS THREAD SAFE, and it is a very simple concept. If somethings state cannot change upon instantiation, no two threads can ever write to the object and break it's state.

The other day I was curious what people thought about this topic. A top hit from DZone claimed not always, and I would like to rebuttal.

Here is a link. https://dzone.com/articles/do-immutability-really-means

And my response:



Yes Java claims that String is immutable. And yes, for all intensive purposes it is. What the writer happens upon is a special case, where a hash property IS MUTABLE.

 122       /** Cache the hash code for the string */
 123       private int hash; // Default to 0

So, the writer is correct that String hash attribute is mutable, and therefore String is not completely immutable. Also note that the Java team guarantees it's thread safety with the writing of it's hashCode() method as thread safe. By making it private they ensure the variable is inaccessible to users and therefore still thread safe.

He also shares an example where his class has it's fields declared final, but the property in his class can hold state.

public class VerySimpleDateFormat {

    private final DateFormat formatter = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);

    public String format(Date d){
        return formatter.format(d);
    }
}

This again, is not the definition of an immutable class. Your class is mutable, since you can change the state of it's properties, just not the direct reference.

Immutable implies thread safety. If a developer writes an Immutable API, we better trust it's claim, and if (for some special case), they have a mutable property in that class, they guarantee it's thread safety and that the property cannot be written to (marked private).

To learn a bit more on immutable classes see my later blog post on the topic.

Comments

Popular posts from this blog

Atmosphere Websockets & Comet with Spring MVC

Microservices Tech Stack with Spring and Vert.X