Video in progress
If an "immutable" record contains a List or a mutable object, how do you get deep immutability, and what does it cost?
A record only makes the references final, which is shallow immutability. Deep immutability needs immutable types or defensive copies at every layer. The price is copying and GC pressure; for large structures that change often, what's left is persistent collections, or "immutable outside, builder inside".
📖 Answer
record Invoice(String no, List<Line> lines, Map<String, String> meta) {}
var list = new ArrayList<Line>();
var inv = new Invoice("A1", list, new HashMap<>());
list.add(new Line(...)); // inv.lines() changed too
A record's equals/hashCode also depend on these mutable fields, so records in a HashSet can "disappear".
The solution, layer by layer:
- Collections: in the compact constructor,
lines = List.copyOf(lines); meta = Map.copyOf(meta);. - Elements:
Linehas to be a record or an immutable class too; otherwise the copy protects the list, not the elements. - Arrays: an array field in a record is almost always a mistake:
equalscompares the reference, and no copy is made. Use aList, orclone()plus an accessor override. - Dates:
java.time(immutable), notjava.util.Date.
Where the cost is:
- every "change" (
withStatus,addLine) is a full copy: O(n). For an invoice with 10 elements it doesn't matter; if a state object with 100 thousand elements is copied on every event, GC and CPU become noticeable; - allocation goes up, but short-lived objects are cheap in the young GC, so don't be afraid until you've measured.
Options for large structures:
- persistent collections (Vavr, PCollections, Clojure's structures): a change is O(log n) and the rest is shared; but the API isn't the standard
List, so there's an interop cost; - mutable inside, read-only outside: the aggregate manages its internal state itself and gives out only an
unmodifiableview; a single thread must own it; - separate the layers: a mutable aggregate inside the domain, and an immutable snapshot at the boundary (an event, an API response, a cache).
My rule: anything shared between threads or used as a cache/event must be deeply immutable, no exceptions. Working state that lives inside a single method can be mutable. You can automate this with ArchUnit or Error Prone's @Immutable check.
Sign up to mark studied questions and save your progress.