Sub topic 13
Immutability: Thread Safety by Design
In earlier chapters, you protected shared data with locks, volatile, and atomic classes. Each tool fixes a problem that comes from shared mutable state. This chapter takes a different approach. If the data can never change, those problems do not happen at all.
What Immutable Means
An immutable object is an object whose state cannot change after it is built. State means the values stored in its fields. Once the constructor finishes, every field keeps the same value for the rest of the object's life.
You already use immutable objects. Java's String is one. When you call toUpperCase(), the original string stays the same. Java gives you a new string instead.
public class StringDemo {
public static void main(String[] args) {
String name = "ada";
String upper = name.toUpperCase();
System.out.println(name); // ada
System.out.println(upper); // ADA
}
}Why Immutability Gives Thread Safety
A race condition needs two things: data that is shared, and at least one thread that writes to it. An immutable object has no writes after construction, so threads can only read it. Reading the same values from many threads at once is safe, and the reads never conflict.
That means:
- You do not need
synchronizedto read an immutable object. - No thread can see a half-finished update, because nothing ever updates.
- Atomicity does not matter here, since there are no compound actions on the object's state.
Building an Immutable Class
Here is a Point class that cannot change after construction.
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);
}
}Each part of the class has a job:
| Rule | In `Point` | Why it matters |
|---|---|---|
| Make the class `final` | `public final class Point` | A subclass could add fields that change. |
| Make fields `private` | `private final int x` | Outside code cannot touch them directly. |
| Make fields `final` | `final int x, y` | The compiler blocks any later assignment. |
| Provide no setters | only `x()` and `y()` | No method changes state. |
| Return new objects for "changes" | `withX` | The original stays the same. |
A final field is a field that can be assigned only once, in the constructor or where it is declared. If you try to assign it again, the code will not compile.
The withX method shows how you "change" an immutable object: you make a new one. The old Point still exists and still has its old values. Any thread holding it sees the same thing it always did.
Using Point From Many Threads
This program shares one Point between two threads with no locks.
public class SharePointDemo {
public static void main(String[] args) throws InterruptedException {
Point shared = new Point(3, 4);
Runnable reader = () -> {
for (int i = 0; i < 3; i++) {
Point moved = shared.withX(shared.x() + i);
System.out.println(Thread.currentThread().getName()
+ " sees " + shared.x() + "," + shared.y()
+ " made " + moved.x() + "," + moved.y());
}
};
Thread t1 = new Thread(reader, "t1");
Thread t2 = new Thread(reader, "t2");
t1.start();
t2.start();
t1.join();
t2.join();
}
}Put Point and SharePointDemo in the same folder, then compile and run them. The lines may print in a different order each time, but shared always shows 3,4. Each thread makes its own new points, so neither thread can disturb the other.
The Special Guarantee of final Fields
Java's memory model, covered in its own chapter later, gives final fields an extra promise. Once a constructor finishes, any thread that gets a reference to the object will see the correct values of its final fields, even if no lock was used to pass the object along.
Plain fields do not get this promise. Without final, another thread could, in rare cases, see a default value such as 0 before the constructor's writes become visible to it. This is a visibility problem, the same kind you saw earlier.
Edge Case: final Does Not Freeze What It Points To
A final field that holds a reference cannot be pointed at a different object. The object it points to can still change.
import java.util.ArrayList;
import java.util.List;
public final class BrokenTeam {
private final List<String> members;
public BrokenTeam(List<String> members) {
this.members = members; // keeps the caller's list
}
public List<String> members() {
return members; // hands out the same list
}
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ada");
BrokenTeam team = new BrokenTeam(names);
names.add("Eve"); // changes the team from outside
team.members().add("Mallory"); // changes it again
System.out.println(team.members()); // [Ada, Eve, Mallory]
}
}BrokenTeam looks immutable, but it is not. The caller keeps the original list and can change it. Anyone who calls members() can also change it.
The Fix: Defensive Copies
A defensive copy is a private copy of incoming or outgoing data, made so outside code cannot change your object's state. Since Java 10, List.copyOf makes an unmodifiable copy in one step.
import java.util.ArrayList;
import java.util.List;
public final class Team {
private final List<String> members;
public Team(List<String> members) {
this.members = List.copyOf(members); // own, unmodifiable copy
}
public List<String> members() {
return members; // safe: it cannot be modified
}
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ada");
Team team = new Team(names);
names.add("Eve");
System.out.println(team.members()); // [Ada]
try {
team.members().add("Mallory");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify team");
}
}
}Two details matter:
- Copy in the constructor, so later changes to the caller's list do not reach you.
List.copyOfreturns a list that throwsUnsupportedOperationExceptiononaddorremove. Returning it is safe.
Collections.unmodifiableList(list) is not the same thing. It wraps the original list without copying it. If someone still holds the original, they can change it, and your "unmodifiable" view will show the change.
The elements need care too. A list of String is fine because strings are immutable. A list of mutable objects, such as StringBuilder, would still let outside code change the contents.
Records: A Shortcut
Java 16 added records. A record is a short way to declare a class that just holds data. Its fields are private and final, the class is final, and there are no setters.
public record Pair(String left, String right) {
public static void main(String[] args) {
Pair p = new Pair("a", "b");
System.out.println(p.left() + p.right()); // ab
}
}Records still need defensive copies for mutable components such as lists. Do the copy in a compact constructor, for example public Pair { list = List.copyOf(list); }, when a component is a list.
Trade-offs
Immutability has a cost. Every "change" creates a new object, which takes memory and some time. For small objects like Point, the cost is usually tiny. For a large structure that changes thousands of times per second, a lock or a concurrent collection may be a better choice.
Also, a variable that holds an immutable object can still be reassigned. If threads share a field like Point current, replacing it is a write to shared state. Make that field volatile, use an AtomicReference, or protect it with a lock. The object is safe to share. The variable that holds it may not be.
Exercise
A class has private final int[] scores; set from a constructor argument, and a getter that returns scores. It has no setters. Is it immutable? If not, how would you fix it?
Show answer
It is not immutable. Arrays are mutable, so the caller can change the array they passed in, and anyone who calls the getter can change its elements. Fix it by copying in the constructor (this.scores = scores.clone();) and returning a copy from the getter (return scores.clone();).
Exercise
Two threads share a field Point location and one thread runs location = location.withX(5);. Point is immutable. Is this code thread-safe?
Show answer
Not fully. Each Point object is safe to share, but the location field is shared mutable state. The other thread may not see the new reference without volatile or a lock. If several threads update it, their read-then-write steps can race. Use volatile for simple publication, or AtomicReference<Point> with updateAndGet for safe updates.