Pure functions and immutability
Memoising an impure function silently gave 5 5 5 where the program meant 5 10 15. And an immutable object seen half-updated: never.
A pure function returns the same output for the same input and changes nothing outside itself. An immutable object cannot change after it is built. These sound like style preferences. They are guarantees, and the guarantees are what let you cache, parallelise and share without thinking — which is the only reason the functional style is worth the effort.
What purity buys, shown by what breaking it costs
Memoisation — remembering a result so you do not compute it twice — is only correct for a pure function. Here it is applied to one of each:
Function<Integer, Integer> square = x -> { calls++; return x * x; };
Function<Integer, Integer> addToRunningTotal = x -> { total += x; return total; };### square(4) three times, memoised: result 16, computed 1 time(s)
### addToRunningTotal(5) three times, memoised: 5 5 5
### addToRunningTotal(5) three times, NOT memoised: 5 10 15square memoised perfectly: same answer, computed once. addToRunningTotal memoised silently changed what the program does — it returned 5 5 5 where the unmemoised version returns 5 10 15. No error. The cache simply assumed the function was pure, and it was not.
That is the practical definition worth carrying. A function is pure when you can replace a call with its result and nothing changes. Everything the functional style offers is a consequence of being allowed to do that:
- Caching is safe only if a call can be replaced by a remembered result.
- Parallelism is safe only if calls do not interfere through shared state — the paradigms lesson's parallel stream that gave three different wrong sums was an impure lambda.
- Testing needs no setup: input in, output checked, nothing to mock.
- Reasoning is local: you understand a pure function by reading it, with no need to know what else ran first.
The side effects that hide
A side effect is anything a function does besides returning a value. The obvious ones are easy to spot; these are not:
- Reading the clock.
LocalDate.now()inside a function makes it return different answers on different days — the flaky tests lesson's first cause. - Reading a mutable field that something else changes. The function does not write it, and it is still impure.
- Throwing on some inputs, in some views of purity. Returning an
Optionalor a result type keeps the failure in the return value. - Logging. Genuinely a side effect, and almost always one worth tolerating. Purity is a spectrum, and logging is where most people sensibly stop.
- Mutating an argument.
sort(list)in place is a side effect on the caller's data.
The move that keeps most code pure without heroics is push the effects to the edges: read the clock, the database and the request once at the boundary, pass the values in, and keep the logic in the middle pure. Then the effectful part is thin and the part with the rules is trivially testable.
// the clock is an input, not something the rule reaches for
boolean isOverdue(Invoice invoice, LocalDate today) {
return invoice.dueDate().isBefore(today);
}Immutability as a concurrency strategy
Here is the concurrency argument, measured. One thread writes a range with lo and hi always equal; another checks whether it ever sees them unequal:
// mutable: two separate writes, observable in between
m.lo = i; m.hi = i;
// immutable: a whole new object, swapped in by one reference write
immutable = new Range(i, i);### mutable object, torn reads seen : 4090
### immutable object, torn reads seen : 0Four thousand and ninety torn reads on the mutable one — moments when the reader saw lo updated and hi not yet. None on the immutable one. No locks anywhere in either.
The reason is structural. A mutable object can be observed between its updates. An immutable object is built completely before anyone can see it, and replacing it is a single reference write — there is no "between" to observe. Nothing to lock, because nothing changes.
That is why the concurrency course reaches for immutable snapshots, why String being immutable makes it safe to share, and why CopyOnWriteArrayList exists: the cheapest lock is the one you do not need.
Making it cheap in Java
Java does not make immutability the default, so it takes a few deliberate habits:
- Records for data: every field
final, no setters,equalsandhashCodegenerated. List.of,Map.of,List.copyOffor collections — unmodifiable, so a returned list cannot be changed by the caller.- Defensive copies at the boundary. A constructor taking a
ListshouldList.copyOfit, or the caller keeps a reference and can mutate "your" immutable object. - "Withers" instead of setters:
order.withStatus(SHIPPED)returns a new object rather than changing this one.
The cost is honest and worth saying: a new object per change is more allocation. For almost all application code the garbage collector makes that invisible, and the concurrency and correctness it buys is far worth it. In a hot loop allocating millions of objects, measure first.
Under the hood: why final fields need no lock
The torn-read measurement above is not a coincidence of timing — the Java Memory Model (JLS §17.5) guarantees it structurally, for any object every one of whose fields is final and that does not let its this reference escape the constructor before it finishes.
An object under construction is, from the memory model's point of view, in a "half-built" state: its fields are being written, and nothing stops another thread from seeing those writes out of order — unless the field is final. For a final field, the JMM inserts a freeze: every thread that later obtains a reference to the object after its constructor returns is guaranteed to see the fully-initialized value of every final field, with no synchronization, no volatile, and no lock. This is the specific guarantee String's immutability, and a record's generated fields, lean on: a record Range(int lo, int hi) compiles lo and hi to private final int fields, and the freeze is why a Range handed to another thread is never observed half-written, exactly what the measurement above showed as zero torn reads against 4,090.
The escape clause matters in practice: the guarantee only holds if the constructor does not leak this — passing this to a listener, starting a thread, or registering a callback before the constructor returns can let another thread see the object before the freeze happens, which is the classic "unsafe publication" bug and the reason constructors that do such things are a design smell independent of immutability.
Try it yourself
What a record's constructor actually generates
record Range(int lo, int hi) {}
Range a = new Range(1, 5);
Range b = new Range(1, 5);
System.out.println(a + " " + b + " " + a.equals(b));Answer
Range[lo=1, hi=5] Range[lo=1, hi=5] true. A record's compiler-generated toString prints the class name and every component in declaration order; equals compares every component's value, not object identity, so two separately constructed records with the same field values are equal even though a != b as references. This is the same generated-equals mechanism the collections course's HashMap lesson assumes when it says a key type needs equals/hashCode — a record gets both for free, derived only from its final components, which is one more reason records are the default shape for immutable data in Java: nobody hand-writes (and nobody forgets to update) equals when a component is added.
Misconceptions
- "An immutable class must be a
record." Records are the concise syntax, but any class with onlyfinalfields, no setters, and defensive copies of any mutable component it holds is just as immutable, and predates records by two decades —String,java.time.LocalDate,BigDecimal. A record is the default choice for a new one, not the only shape. - "Immutability and
finalfields are the same guarantee."finalon a field prevents reassignment; the JMM's freeze guarantee — safe publication with no lock — only applies when every field isfinalandthisdoes not escape the constructor. A class with nineteenfinalfields and one mutable one gets none of that guarantee for free.
Sources
- The Java Language Specification, §17.5 ("Final Field Semantics") — the freeze guarantee for
finalfields and the constructor-escape condition it depends on. - JEP 395 (Records) — the generated
equals,hashCodeandtoString, and the canonical constructor. - Brian Goetz et al., Java Concurrency in Practice, chapter 3 ("Sharing Objects") — safe publication and immutability as a concurrency strategy.