Sub topic 13
Immutability: Thread Safety by Design
Earlier chapters fixed race conditions with locks. Locks work, but you can get them wrong, and they slow threads down. This chapter shows a different approach. If an object can never change, threads cannot fight over it.
What Is an Immutable Object?
An immutable object is an object whose state cannot change after it is built. Its state is the values stored in its fields.
A race condition needs two things: data that is shared, and data that changes. Immutability removes the second one. Many threads can read the same value at the same time, and each one sees the same thing. No thread ever writes, so there is nothing to collide with.
You already use immutable classes in Java. String and Integer are both immutable.
How to Build an Immutable Class
Follow these rules:
- Mark the class
final, so no subclass can add changing behavior. - Mark every field
privateandfinal. A final field is a field that is assigned once, in the constructor, and never again. - Provide no setters. A setter is a method that changes a field.
- To "change" a value, return a new object instead.
Here is a point on a grid built this way:
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int x() {
return x;
}
public int y() {
return y;
}
public Point withX(int newX) {
return new Point(newX, y);
}
}The withX method does not touch the original point. It makes a fresh Point with the new x and the old y.
public class PointDemo {
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = a.withX(10);
System.out.println(a.x() + "," + a.y()); // 1,2
System.out.println(b.x() + "," + b.y()); // 10,2
}
}Why final Matters for Threads
The final keyword does more than block reassignment. The Java Memory Model, covered in a later chapter, promises that once a constructor finishes, every thread that sees the object also sees the correct values of its final fields. No synchronized or volatile is needed.
Watch Out for Mutable Fields
A final field that refers to a mutable object, such as an ArrayList, only freezes the reference. The list itself can still change. To keep the class immutable, copy the list in the constructor and never hand out the original. List.copyOf(list) gives you an unmodifiable copy.
| Field type | Immutable if final? |
|---|---|
| `int`, `long`, `boolean` | Yes |
| `String`, `Integer` | Yes |
| `ArrayList`, arrays | No, copy them first |
Exercise
A class has a private final field int[] scores and a getter that returns scores. Is the class immutable? Why or why not?
Show answer
No. The final keyword only stops the field from pointing to a different array. Any caller of the getter can change the array's elements. Copy the array in the constructor, and return a copy from the getter, for example with scores.clone().
Exercise
Two threads share one Point object. One thread calls p.withX(5). Can the other thread see p's x change to 5?
Show answer
No. withX returns a new Point and never modifies p, so p.x() stays the same for every thread.