Java Immutability and How to Build Immutable Classes
Build truly immutable Java classes with final fields, defensive copies and records, and see why shallow immutability fails and why it is thread safe.

Mutable state is the source of most bugs that take a long time to find. An object changes in one place and the effect appears in another, through a reference nobody remembered was shared. Immutable objects remove the whole category: once built, they never change, so they can be shared, cached, used as map keys and passed between threads without anyone needing to think about it. Java's String, Integer, BigDecimal, LocalDate and every record are immutable, and writing your own value classes the same way is among the cheapest improvements to a codebase. This post builds an immutable class by hand, shows why the obvious version leaks, introduces records and their limit, compares immutable collection options and covers how to change an immutable object. It builds on the concurrency rules in the thread safety checklist.
The hand written recipe
Five rules make a class immutable, and breaking any one of them breaks the guarantee:
- Declare the class
final, so a subclass cannot add mutable state or override methods. - Make every field
privateandfinal. - Provide no setters or any method that modifies state.
- Copy any mutable object passed to the constructor.
- Never return a mutable internal object; return a copy or an immutable view.
Here is a first attempt that looks right and is not:
package dev.javahacks.model;
import java.util.Date;
import java.util.List;
public final class Order {
private final String id;
private final Date placedAt; // mutable type
private final List<String> items; // mutable type
public Order(String id, Date placedAt, List<String> items) {
this.id = id;
this.placedAt = placedAt; // leak: stores the caller's object
this.items = items; // leak: stores the caller's list
}
public String id() { return id; }
public Date placedAt() { return placedAt; } // leak: hands out the internal object
public List<String> items() { return items; } // leak: hands out the internal list
}All fields are final, and a caller can still change the order:
List<String> items = new ArrayList<>(List.of("book"));
Order order = new Order("A-1", new Date(), items);
items.add("laptop"); // the order now contains a laptop
order.items().clear(); // and now it is empty
order.placedAt().setTime(0); // and it was placed in 1970final on a field means the *reference* cannot be reassigned, not that the object it points to is frozen. That is the central misunderstanding about immutability in Java.
The fixed version
Copy on the way in, and return copies or unmodifiable collections on the way out:
package dev.javahacks.model;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
public final class Order {
private final String id;
private final Instant placedAt; // immutable type
private final List<String> items;
public Order(String id, Instant placedAt, List<String> items) {
this.id = Objects.requireNonNull(id);
this.placedAt = Objects.requireNonNull(placedAt);
this.items = List.copyOf(items); // independent, unmodifiable copy
}
public String id() { return id; }
public Instant placedAt() { return placedAt; }
public List<String> items() { return items; } // already unmodifiable, safe to return
public Order withItem(String item) {
var next = new java.util.ArrayList<>(items);
next.add(item);
return new Order(id, placedAt, next);
}
}Replacing Date with Instant removes one defensive copy entirely, which is the best kind: choose immutable field types and there is nothing to protect. For the collection, List.copyOf makes an independent unmodifiable list, so later changes to the caller's list do not appear, and calling add on order.items() throws UnsupportedOperationException, the message to expect when a caller tries, covered in fixing UnsupportedOperationException on immutable lists. Note that List.copyOf also rejects null elements with a NullPointerException, a deliberate property of the immutable collection factories.
Records: most of it for free
A record declares the fields, the constructor, the accessors, equals, hashCode and toString in one line:
public record Order(String id, Instant placedAt, List<String> items) {
public Order { // compact canonical constructor
Objects.requireNonNull(id);
Objects.requireNonNull(placedAt);
items = List.copyOf(items); // reassigns the parameter, then the field is set
}
}A record is implicitly final, its fields are private final and there are no setters. But the guarantee stops at the field. A record with a List component is shallowly immutable: the field cannot be reassigned, though the list can change, unless you copy it, as the compact constructor does above. The same applies to arrays (record Image(byte[] pixels) exposes the array), mutable beans and Date. When you design a record, ask of each component whether its type is itself immutable, and copy it if not. The accessor then needs no copy, since the stored list is already unmodifiable.
Unmodifiable views versus copies
Java has two things that look alike. Collections.unmodifiableList(list) returns a view: a wrapper that rejects modification through the wrapper, while the underlying list can still change.
List<String> source = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(source);
List<String> copy = List.copyOf(source);
source.add("c");
System.out.println(view); // [a, b, c] the view follows the source
System.out.println(copy); // [a, b] the copy is independentFor a field in an immutable class you need the copy, not the view. A view is the right tool when you want to expose your own internal mutable list read only to callers, which is a different goal: protecting a class's internals, not making it immutable. List.of, Set.of, Map.of and the copyOf methods all give true immutable collections, with the elements' own mutability still your concern.
Changing an immutable object: withers
Immutability does not mean values never change; it means a change produces a new object. The convention is a withX method returning a modified copy, as withItem does above. For records with many components, a builder or a set of withers keeps updates readable:
public record Address(String street, String city, String postcode) {
public Address withCity(String newCity) {
return new Address(street, newCity, postcode);
}
}
Address moved = address.withCity("Da Nang");Creating a new object per change costs allocation, and modern JVMs make short lived objects cheap; the cost matters only in a hot loop, where a mutable builder used locally and frozen at the end is the standard compromise. StringBuilder producing an immutable String is exactly this pattern.
Why it is worth it
Thread safety without locks. An object whose state cannot change after construction needs no synchronisation, provided it is safely published, which a final field guarantees. All fields final means other threads see the fully constructed object. No race can corrupt it, because there are no writes. That is why immutable value classes are the first recommendation of the thread safety checklist.
Safe map keys and set members. A HashMap key whose fields change after insertion is lost in the wrong bucket forever, and the entry becomes unreachable. Immutable keys cannot do that, which is why String and Integer are the usual keys. A matching equals and hashCode contract is in writing a correct equals and hashCode.
Easier reasoning and testing. A function taking an immutable argument cannot change it, so callers need not defend against it, and tests compare values with equals.
Cache friendliness. Immutable objects can be cached and shared freely, as the JDK does with the Integer cache and string interning.
Where it gets harder
Large aggregates. Copying a hundred-field object to change one field is tedious by hand; use a builder, a generator such as Immutables, or records with with methods generated by a tool. Lombok's @Value and @With produce the same, and the choices are compared in Lombok, records and Immutables.
Frameworks that require setters. Hibernate entities are intentionally mutable and have a no-argument constructor; do not force immutability onto entities. Use immutable DTOs and value objects around them. Jackson can read records and constructors with @JsonCreator.
Deep immutability of third-party types. Many library classes are mutable. Wrap them or copy at the boundary, and document the choice.
Serialization. Immutable classes with a final-only constructor work with readObject only through serialization proxies; if you must serialize them, see Java serialization risks.
Testing immutability
A cheap test confirms the defensive copying you wrote:
@Test
void orderIsNotAffectedByChangesToTheInputList() {
var items = new ArrayList<>(List.of("book"));
var order = new Order("A-1", Instant.parse("2026-11-03T08:00:00Z"), items);
items.add("laptop");
assertThat(order.items()).containsExactly("book");
}
@Test
void itemsCannotBeModifiedThroughTheAccessor() {
var order = new Order("A-1", Instant.now(), List.of("book"));
assertThatThrownBy(() -> order.items().add("laptop"))
.isInstanceOf(UnsupportedOperationException.class);
}When this does not apply
Do not make an object immutable when it is naturally a long lived mutable entity with identity, like a JPA entity, a connection or a session, or when profiling shows copying dominates a hot path. Large mutable buffers are mutable for performance reasons. The goal is to make *values* immutable and to confine mutation to a few clearly owned places. See Joshua Bloch's *Effective Java* on minimising mutability, the Java Tutorial on immutable objects and the JDK documentation for List.copyOf) for the rules.


