2

I'm reading the Effective Java book and on the chapter on minimizing mutability Item 15. Maybe I'm having trouble understanding the concept of thread-safety since I'm not experienced much in concurrency. Could I get an example that illustrates how an immutable object is always thread-safe?

Thank you in advance!

4 Answers 4

3

Immutable objects are threadsafe because they cannot be modified.

It doesn't matter if a million threads access the same object at the same time, because none of the threads can mutate the object.

1
  • More precisely - immutable objects can't be modified and everyone (i.e. all the threads) will always be reading the same values, therefore, immutable objects are thread-safe.
    – happymeal
    May 16, 2014 at 3:42
2

Thread safe means that changing said object doesn't have adverse effects on other threads that are using that object. Immutable objects cannot be changed. Hence, by design, immutable objects are thread safe because no change can happen to them to begin with.

Keep in mind, threads might share references. If you change which object the reference points to (not changing the object itself but reassigning the reference to another object all together with the = sign), then thread safety is jeopardized.

4
  • The only way two Java threads can "share a reference" is through a field of some object that both threads know about. If they can "change which object the reference points to," that means the common object is a mutable object. May 20, 2014 at 17:07
  • 1
    No it doesn't. Changing where a reference points is to create a new object and assign its address to said reference. If you talk of manipulating an object, said object is mutable. Keep in mind Strings are IMmutable, you can easily make them reference another object.
    – Chad
    May 21, 2014 at 0:16
  • you are conflating objects with variables. When we say, "Strings are immutable", we are talking about instances of the String class, but when you say "you can make them reference another object", you are talking about String variables. My point was, the only way two threads can use the same variable is if it is a field of some object, and if the threads can update the field, then the object is mutable, and it may (depending on your design) require synchronization to behave properly. May 21, 2014 at 13:45
  • I am not conflating objects with variables... You're misunderstanding what I'm saying entirely. An object IS an instance of a class. To say a string is immutable means you cannot change the in-memory instance (is object). Re-read my explanation or (better yet) the Java documentation and Oracle tutorials. Ergo, your point saying "if two threads can update the field, then it is mutable" is INCORRECT. You're thinking about it backwards. If the object is immutable, then two threads can't update it to begin with. That's the DEFINITION OF IMMUTABLE.
    – Chad
    May 22, 2014 at 9:40
0

Say you have a counter:

class Counter {
    private int counter = 0;

    public void increment() {
        counter++;
    }

    public int getCounter() {
        return counter;
    }

}

And say this is your main method:

public static void main(String[] args) {
    final Counter counter = new Counter();
    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(4);
    final Runnable r = () -> {
        try {
            startLatch.await();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 100; i++) {
            counter.increment();
            if (counter.getCounter() % 10 == 0) {
                System.out.println(counter.getCounter());
            }
        }
        endLatch.countDown();
    };
    new Thread(r).start();
    new Thread(r).start();
    new Thread(r).start();
    new Thread(r).start();
    startLatch.countDown();
    try {
        endLatch.await();
    } catch (final InterruptedException e) {
        e.printStackTrace();
    }
}

It's long, but basically all it does is create a single Counter, and then creates 4 threads that increment the counter a hundred times each, and prints the counter's value if the value is a multiple of 20. What output do you get?

20
40
60
80
100
141 // <-- Huh? Not a multiple of 20?
120 // <-- What's up with the order here?
180
220
240
160 // <-- This is way out of place...
280
300
260
200
320
340
360
380
    // <-- missing 400?

Well that's a surprise. Wrong values, values out of place, etc...

The thing is that sharing objects with mutable state like Counter presents a lot of difficulties. You have to deal with locks, synchronization, etc. to get a mutable object to behave properly. In this case, synchronization is relatively easy, but making complicated objects synchronize right is hard. Take a look at the classes in java.util.concurrent if you want an example.

The nice thing about immutable objects is that they avoid this problem because they can't be modified. So no matter how many threads are doing something to an immutable object, you can be absolutely sure that it won't change, so you won't deal with strange results like this. An immutable Counter would be fairly useless, but something like a String that is immutable and can be shared across threads without worrying about synchronizing changes across threads is very useful in the concurrent world.

0

You can make a object immutable by removing all setters and any methods that change state of an object.

String is example of immutable object. No matter how many threads access a String they cannot change it. Anytime you modify a String a new object is created.

So multiple threads can read the state but can never update the state.

1
  • An object is effectively immutable if all of its fields are private, and none of its methods updates any of its fields. That is subtly different from a truly immutable object whose fields are all final. The difference is, the effectively immutable object is only thread safe if it is safely published. Google for "Java" and "safely published" to learn more. May 20, 2014 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.