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.