- Prerequisites
- 7.1 Immutable Collections · B1V1 5.1 Encapsulation
- Covers
- Defensive copying · Structural immutability
- Related
- 5.4 Equality & Hashing · B2V4 (safe publication) · Book 5 (value objects, DDD)
On this page
1Concept / Definition
An immutable object has state that cannot change after construction. For objects that contain collections or other mutable parts, immutability has to be designed: the object must copy mutable inputs so callers cannot change them afterwards, must not expose its internals for modification, and must be structurally closed — final fields, no mutators, no subclasses adding state. Done properly, the object is thread-safe and can be shared freely.
2Why It Exists
A class that stores a caller's list directly is only as safe as the caller's discipline: a later list.add in the caller silently changes the object's state, bypassing validation. Returning an internal list lets any client modify it. These aliasing bugs are hard to trace and become data races in concurrent code. Immutable design removes the whole class of problems.
3Core Concepts
Defensive copying
Copy mutable inputs when they enter the object — in constructors, factories and setters of builders — and validate the copy, not the original, so a caller cannot change the data between validation and copying (a time-of-check/time-of-use bug). Protect state on the way out by returning immutable collections or copies. With immutable collections, both steps become cheap: List.copyOf does nothing if the input is already immutable, and an immutable internal list can be returned directly.

Structural immutability
Structural immutability means that no code path can change the object's state: the class is final (or a record, or has only private constructors), every field is private final, there are no setters — changes produce new instances ("withers") — mutable inputs are copied, and internals are never leaked. The object is then deeply immutable only if every component is itself immutable; an immutable list of mutable objects is only shallowly immutable.


4How It Works Internally
The Java Memory Model gives final fields a special guarantee: once a constructor finishes, any thread that obtains a reference to the object sees the final fields' values as set in the constructor, without synchronisation — provided this did not escape during construction. This is why properly constructed immutable objects are thread-safe by construction (B2V4). Records are a compact way to get final fields, but their compact constructors must still copy mutable components.

5APIs / Features / Syntax
Immutable design uses ordinary language features; what matters is applying all of them together. The tools, and what each contributes:
| Feature | Since | What it gives |
|---|---|---|
| final class, private final fields | Java 1.0 | No subclass can add state; fields set once |
| record | Java 16 | Final class, private final fields, accessors, equals/hashCode/toString |
| Compact constructor: Order { lines = List.copyOf(lines); } | Java 16 | Copy and validate before the fields are assigned |
| List.copyOf / Set.copyOf / Map.copyOf | Java 10 | Defensive copy that is free for immutable input |
| array.clone(), Arrays.copyOf | Java 1.0 / 6 | Copies of arrays, in and out |
| sealed interfaces with record implementations | Java 17 | A closed set of immutable variants |
| "Wither" methods: withLine(...) | convention | Change = a new instance; the old one stays valid |
Records do the structural part automatically, but not the defensive part: a record copies nothing, and for array components its generated equals compares references (Q9). Time types from java.time, String, the boxed primitives, BigDecimal and the immutable collections are safe component types; Date, arrays, StringBuilder and mutable collections are not.
6Practical Examples
Example 1 — From aliasing bugs to structural immutability
Problem. An Order class stores the caller's list and returns it from its accessor, so both the caller and every reader can change the order behind its back. The box shows the broken class and the fixed record, and how arrays need the same care.
// Broken: aliasing in both directions
public final class Order {
private final List<Line> lines;
// stores caller's list
public Order(List<Line> lines) { this.lines = lines; }
public List<Line> lines() { return lines; } // leaks internal list
}
// Fixed with a record and a compact constructor
public record Order(OrderId id, List<Line> lines) {
public Order {
Objects.requireNonNull(id);
lines = List.copyOf(lines); // copy first (also rejects nulls)
// validate copy
if (lines.isEmpty()) throw new IllegalArgumentException("no lines");
}
public Order withLine(Line line) { // "wither": new instance
List<Line> next = new ArrayList<>(lines);
next.add(line);
return new Order(id, next);
}
}
// immutable elements → deep immutability
public record Line(Sku sku, int qty, Money price) {}
// Arrays need explicit copies: records do not copy them for you
public record Checksum(byte[] bytes) {
public Checksum { bytes = bytes.clone(); }
@Override public byte[] bytes() { return bytes.clone(); }
// also override equals/hashCode with Arrays.equals / Arrays.hashCode
}Why it works. List.copyOf in the compact constructor cuts the link to the caller's list and returns an immutable list, so the accessor can hand it out without a copy. Validation runs on the copy, and withLine builds a new Order through the same constructor, so every instance passes the same checks. Checksum clones its array on the way in and on the way out, because a record would otherwise expose the array itself.
Example 2 — Mini program: an immutable order, end to end
Problem. The fixed Order must hold up against every kind of misuse: a caller that keeps changing its list, a reader that tries to add a line, an update, and use as a HashMap key. The program checks each one.
public class ImmutableOrder {
record Line(String sku, int qty, long cents) {
Line {
if (qty <= 0) throw new IllegalArgumentException("qty " + qty);
}
}
record Order(String id, List<Line> lines) {
Order {
Objects.requireNonNull(id, "id");
lines = List.copyOf(lines); // 1. copy first ...
if (lines.isEmpty()) // 2. ... then validate
throw new IllegalArgumentException("no lines");
}
Order withLine(Line l) { // 3. change = new object
List<Line> next = new ArrayList<>(lines);
next.add(l);
return new Order(id, next);
}
long total() {
return lines.stream().mapToLong(l -> l.qty() * l.cents()).sum();
}
}
public static void main(String[] args) {
List<Line> input = new ArrayList<>(List.of(new Line("pen", 2, 150)));
Order order = new Order("o-1", input);
input.add(new Line("ink", 1, 900)); // caller changes its list
System.out.println("order lines " + order.lines().size()
+ ", total " + order.total());
try {
order.lines().add(new Line("pad", 1, 300)); // reader tries
} catch (UnsupportedOperationException e) {
System.out.println("lines().add: UnsupportedOperationException");
}
Order bigger = order.withLine(new Line("pad", 1, 300));
System.out.println("old total " + order.total()
+ ", new total " + bigger.total());
Map<Order, String> status = new HashMap<>(); // safe as a map key
status.put(order, "PAID");
Order same = new Order("o-1", List.of(new Line("pen", 2, 150)));
System.out.println("equal value finds entry: " + status.get(same));
}
}order lines 1, total 300
lines().add: UnsupportedOperationException
old total 300, new total 600
equal value finds entry: PAIDWhy it behaves this way. The order took a copy of the one-line list, so the caller's later add does not reach it and the total stays 300. The accessor returns the immutable copy, so the reader's add throws. withLine returns a second order with a total of 600 and leaves the first unchanged. Because the state cannot change, the record's value-based equals and hashCode are stable, and an equal order built separately finds the map entry.
Example 3 — Copy first, then validate
Problem. Section 3 says that validating the caller's collection before copying it lets invalid data in. A real attack or race needs another thread; this program simulates it deterministically with a list that changes between the check and the copy.
public class ToctouDemo {
/** Stands in for a list another thread changes between two reads. */
@SuppressWarnings("serial")
static final class ShiftingList extends ArrayList<Integer> {
private int reads;
ShiftingList(List<Integer> init) { super(init); }
@Override public Object[] toArray() { // List.copyOf reads here
if (++reads == 1) add(-50); // "meanwhile": bad value
return super.toArray();
}
}
static List<Integer> validateThenCopy(List<Integer> qty) {
for (int q : qty)
if (q <= 0) throw new IllegalArgumentException("" + q);
return List.copyOf(qty); // copies what changed
}
static List<Integer> copyThenValidate(List<Integer> qty) {
List<Integer> copy = List.copyOf(qty);
for (int q : copy)
if (q <= 0) throw new IllegalArgumentException("" + q);
return copy; // checked = stored
}
public static void main(String[] args) {
System.out.println("validate, then copy: "
+ validateThenCopy(new ShiftingList(List.of(3, 5))));
try {
copyThenValidate(new ShiftingList(List.of(3, 5)));
} catch (IllegalArgumentException e) {
System.out.println("copy, then validate: rejects "
+ e.getMessage());
}
}
}validate, then copy: [3, 5, -50]
copy, then validate: rejects -50Why it behaves this way. validateThenCopy checks the caller's list, and by the time List.copyOf reads it, it contains -50, which is stored although it was never checked. copyThenValidate checks the private copy, the exact data it will keep, so the bad value is rejected (Figure 5).

7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Validating the caller's collection, then copying | The caller can change it in between, and unchecked data is stored (Example 3) | Copy first, then validate the copy |
| Records with List or array components that are not copied | Records are shallowly immutable by default: callers change the record through their reference (Q7) | List.copyOf in the compact constructor; clone arrays in and out |
| Returning Collections.unmodifiableList(internalMutableList) and then mutating the internal list | Callers see the changes, possibly half-done while another thread writes | Keep an immutable list and replace it on change |
| Immutable containers of mutable elements (e.g. java.util.Date) | The container cannot change but its elements can | Use immutable element types: Instant, records, String |
| Letting this escape from the constructor (registering listeners, starting threads) | Other threads can see the object before its final fields are frozen | Register or start in a factory method after construction |
| Array components left with the record's generated equals and hashCode | Equal contents compare unequal; set and map lookups fail (Q9) | Override equals/hashCode with Arrays.equals / Arrays.hashCode |
| Mutable objects used as HashMap keys or HashSet elements | Changing a key after insertion strands the entry in the wrong bucket (5.4) | Use immutable keys: records of immutable components |
8Performance & Production Considerations
Copying costs allocation proportional to size, which is negligible for typical domain objects and cheap when inputs are already immutable. For large collections updated frequently, copying on every change can become expensive; persistent (structurally shared) collections from libraries, or a mutable builder that produces an immutable result, address this. The payoff — no locking, safe caching, easy reasoning — usually dominates.
9Architecture & Design Considerations
Immutable objects are the natural representation of value objects and events in domain-driven design, of messages between services, and of configuration. They make concurrency safer, caching trivial and debugging easier because state cannot change behind your back. The general architectural rule: make data immutable by default, confine mutation to clearly owned places (aggregates, builders, local variables), and cross every boundary — thread, layer, service — with immutable data.
10Interview Questions & Answers
What is a defensive copy?
A copy of a mutable object made when it enters or leaves a class, so external code cannot change the class's internal state through a shared reference.
What makes a class immutable?
A final class (or record), private final fields, no mutators, defensive copies of mutable inputs, no leaking of mutable internals, and — for deep immutability — immutable components.
Is a record automatically immutable?
Its fields are final, so it is shallowly immutable. If a component is a mutable List or array, the record must copy it in a compact constructor (and for arrays, in the accessor) to be truly immutable.
Why should you copy before validating?
If you validate the caller's object first, the caller (possibly another thread) can modify it after validation but before the copy, so invalid data enters the object. Copying first means you validate exactly what you store.
Why are immutable objects thread-safe?
Their state never changes after construction, so there are no writes to race with. The Java Memory Model guarantees that final fields set in the constructor are visible to all threads once construction completes, provided this does not escape during construction.
How would you apply immutability across a service's architecture?
Use immutable records for DTOs, events, value objects and configuration; keep mutable state inside clearly owned aggregates or builders; return immutable collections from APIs; and treat data crossing threads, layers and services as immutable. This reduces locking, simplifies caching and makes behaviour easier to reason about.
What does this program print?
public class RecordAliasQuiz {
record Team(String name, List<String> members) {}
public static void main(String[] args) {
List<String> people = new ArrayList<>(List.of("ann"));
Team t = new Team("core", people);
people.add("raj");
t.members().add("li");
System.out.println(t.members().size() + " " + people.size());
}
}It prints 3 3. The record stores the reference it was given, so people and t.members() are the same ArrayList; the caller's add and the reader's add both change it. A compact constructor with members = List.copyOf(members); would make the record print 1, and the reader's add would throw.
What is a "wither", and why do immutable classes use them?
A method such as withLine(line) or withStatus(PAID) that returns a new instance with one value changed and leaves the original untouched; String.replace and LocalDate.plusDays follow the same pattern. Withers are how an immutable object supports change without mutation: every new instance goes through the constructor, so it passes the same validation, and code that still holds the old instance is unaffected.
What does this program print?
public class ChecksumQuiz {
record Digest(byte[] bytes) {}
public static void main(String[] args) {
byte[] b = {1, 2, 3};
Digest d1 = new Digest(b), d2 = new Digest(b.clone());
Set<Digest> seen = new HashSet<>(List.of(d1));
System.out.println(d1.equals(d2) + " " + seen.contains(d2) + " "
+ Arrays.equals(d1.bytes(), d2.bytes()));
}
}It prints false false true. A record's generated equals compares each component with Objects.equals, which for arrays is reference equality, and its hashCode uses the array's identity hash. Two digests with equal bytes in different arrays are therefore unequal, and the set cannot find the second. Only Arrays.equals compares contents, which is why the Checksum record in Example 1 must override both methods.
What exactly does the final-field rule of the Java Memory Model guarantee, and what does it not?
When a constructor completes, its final fields are frozen: any thread that later obtains a reference to the object, even through a data race, sees those fields and the objects reachable through them as they were at the end of the constructor (Figure 4). It does not cover non-final fields, changes made to the referenced objects after construction, or a reference to this that escaped during construction. Immutable objects avoid all three, which is why they need no synchronisation.
Cache hit rates fall and memory grows after a release. Investigation shows the cache key is a class holding a mutable List of filter values that callers change after the lookup. Explain and fix.
The key's hashCode depends on the list. When a caller changes the list after the entry was stored, the entry stays in the bucket of the old hash code, so lookups with equal keys miss, and new entries are added for "the same" key, which explains both symptoms. Make the key an immutable record whose compact constructor applies List.copyOf to the filters, or normalise the filters into a sorted, immutable form, and bound the cache size so that such a bug cannot exhaust memory.
Your JPA entities are mutable, as the framework expects. Should the domain model be immutable anyway?
Mutable entities suit dirty checking, lazy loading and proxies; an immutable domain model needs mapping code but can be shared, cached and tested without surprises. A common middle way keeps entities mutable inside the persistence layer, uses immutable records for value objects and for everything that crosses a boundary (DTOs, events), and never exposes entity collections directly.
How do you design the event types that dozens of services publish and consume?
Make every event a deeply immutable record of immutable components: ids, Instant timestamps, BigDecimal amounts, List.copyOf collections, with validation in the compact constructor. Version the schema explicitly and evolve it additively, so old consumers ignore new fields. Publish facts, not commands, and never update a published event: corrections are new events. In Java, a sealed interface of event records lets consumers switch over the variants exhaustively, and the immutability in code mirrors the append-only log at system level (section 9).
An aggregate holds 50,000 immutable lines and is updated many times a second. Every wither copies the whole list. What do you do?
Each update then does O(n) copying and creates garbage. Batch changes in a mutable builder and publish one immutable result per batch, use a persistent collection whose updates share structure (O(log n) copying), or split the aggregate into smaller parts. Inside a single owner, controlled mutation behind a narrow API is acceptable if measurements justify it; keep immutability at the boundaries.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Copy mutable inputs first, then validate the copy.
- Return immutable collections; never leak mutable internals.
- Structural immutability: final, private final fields, no mutators, withers.
- Records are shallowly immutable — copy List and array components.
- Deep immutability needs immutable elements too.