I am a Java Developer working in Sydney. I am eager to learn new technologies, new frameworks, new languages. Thibault has posted 8 posts at DZone. You can read more from them at their website. View Full User Profile

Does Immutability Really Mean Thread Safety?

10.03.2012
| 11578 views |
  • submit to reddit
I have often read articles saying "If an object is immutable, it is thread safe".  But I have never found an article that convinces me that 'immutable' means thread safety. Even the book by Brian Goetz Java Concurrency in Practice with its chapter on immutability did not fully satisfiy me. In this book we can read word for word, in a frame : Immutable objects are always thread-safe. I think this sentence deserves more explanation. So I am going to try to define immutability and its relation to thread safety.

Definitions

Immutability

My definition is "An immutable object is an object that will not change its state after its construction". I am deliberately vague, since no one really agrees on the exact definition.

Thread safety

You can find a lot of different definitions of "thread safe" on internet. It's actually very tricky to define it. I would say that thread safe code has an expected behavior in multi-thread environment. I'll let you define "expected behavior"...

The String example

Lets have a look at the code of String (actually just a part of the code...):

public class String {
    private final char value[];

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

    public String(char[] value) {
        this.value = Arrays.copyOf(value, value.length);
    }

    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
}
String is considered immutable. Looking at its implementation, we can deduce one thing: an immutable string can change its internal state (in this case, the hashcode which is lazy loaded) as long as it is not externally visible. Now I am going to rewrite the hashcode method in a non-thread safe way:
    public int hashCode() {
        if (hash == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                hash = 31 * hash + val[i];
            }
        }
        return hash;
    }
As you can see, I have removed the local variable h and I have instead affected the variable hash directly. This implementation is NOT thread safe! If several threads call hashcode at the same time, the returned value could be different for each thread. The question is, 'is this class immutable?' Since two different threads can see a different hashcode, in an external point of view we have a change of state and so it is not immutable. We can so conclude that String is immutable because it is thread safe and not the opposite. So... What's the point of saying "Use an immutable object, it is thread-safe! But take care, you have to make your immutable object thread-safe!"?

The ImmutableSimpleDateFormat example

Below, I have written a class similar to SimpleDateFormat.
public class VerySimpleDateFormat {

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

    public String format(Date d){
        return formatter.format(d);
    }
}
This code is not thread safe because SimpleDateFormat.format is not. Is this object immutable? Good question! We have done our best to make all fields not modifiable, we don't use any setter or any methods that let us suggest that the state of the object will change. Actually, internally SimpleDateFormat changes its state, and that's what makes it non-thread safe. Since something changed in the object graph, I would say that it's not immutable, even if it looks like it...

The problem is not even that SimpleDateFormat changes its internal state, the problem is that it does so in a non-thread safe way. In conclusion, it is not that easy to make an immutable class. The final keyword is not enough. You have to make sure that the object fields of your object don't change their state, which is sometimes impossible.

Immutable objects can have non thread-safe methods (No magics!)

Let's have a look at the following code.
public class HelloAppender {

    private final String greeting;

    public HelloAppender(String name) {
        this.greeting = "hello " + name + "!\n";
    }

    public void appendTo(Appendable app) throws IOException {
        app.append(greeting);
    }
}
The class HelloAppender is definitely immutable. The method appendTo accepts an Appendable. Since an Appendable has no guarantee to be thread-safe (eg. StringBuilder), appending to this Appendable will cause problems in a multi-thread environment.

Conclusion

Making objects immutable is definitely a good practice in some cases and it helps a lot to make thread-safe code. But it bothers me when I read everywhere Immutable objects are thread safe, displayed as an axiom. I get the point but I think it is always good to think a bit about that in order to understand what causes non-thread safe code. Since I am not fully satisfied by the sentence Immutable objects are thread safe, I finish this article with my own sentence:  Immutable objects ease concurrency programming.
Published at DZone with permission of its author, Thibault Delor.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Wojciech Kudla replied on Wed, 2012/10/03 - 4:36pm

I think you confuse two separate concepts. Immutability provides thread-safety for the scope of the subjected object, not for external objects as in your HelloAppender example.
How did you arrive at the conclusion that immutable objects that expose behavior driven by some external non-immutable or non-thread-safe entities should be thread-safe?
I'd suggest getting back to reading Java Concurrency in Practice. Chances are you missed the context of thread-safety provided by immutability.  

Thibault Delor replied on Wed, 2012/10/03 - 10:14pm in response to: Wojciech Kudla

You are right, I think you misunderstand my point. I often read "Immutable objects are thread safe" without explanation and the goal of my article is to say "Warning, you have to think twice about what that mean and don't think that if you do an immutable object you can just ignore the thread-safety issue". 

Anyway, thank you for your comment and your clarification. 

Barry Smith replied on Thu, 2012/10/04 - 5:21am

Surely the point here is that String is not a true immutable? The fact is that the hash values changes *after* construction. If the hash were set at construction time the issue would not exist. True immutables are thread safe. The trick is to actually make immutables immutable.

Uberto Barbini replied on Thu, 2012/10/04 - 3:23pm

The point is not that you made String thread unsafe, you made it mutable (for the hash part) so it's no more thread safe.

Note that the original lazy loading implementation is thread safe because also if 2 threads start to compute the hash in parallel they will come to the same result so no problem.

An object is immutable, if it can present only one state to the other objects, no matter how and when they call its methods.
If so it's thread-safe by any definition of thread-safe.

Uberto Barbini replied on Thu, 2012/10/04 - 3:26pm

Also in the second example, maybe Appendable is unsafe, if so don't use it in a multithread enviroment.
Still you're immutable object is thread-safe. Thread-safeness is not contagious! :)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.