Immutability in Java 21: Records, Defensive Copying, and Collections
Part of the series “Java 21 & Spring Boot” · part 1 of 5
- Immutability in Java 21: Records, Defensive Copying, and Collections
- Modern Spring Boot with Java 21 — Virtual Threads, ScopedValue, and Structured Concurrency
- Java Virtual Threads Are a Bigger Deal Than You Think
- Spring Boot + JPA + Virtual Threads (Java 21): Avoid N+1, OSIV & Pagination Pitfalls
- The Complete Guide to RestClient in Spring Boot 3.2 with Java 21 Virtual Threads
On this page
If you’ve been writing Java for a while, you probably think you know how to write immutable classes.
final fields? Check.
No setters? Check.
Thread-safe? …maybe?
Once collections enter the picture, most “immutable” Java classes quietly stop being immutable.
With Java 21, we finally have a clean, correct, and expressive way to solve this problem using records and **List.copyOf()**. Let’s walk through it the right way.
What Does “Immutable” Actually Mean?
An object is immutable if its state cannot change after construction.
That means:
- No field values change
- No internal objects can be modified
- External code cannot affect internal state
Immutability gives you:
- Thread safety for free
- Fewer bugs
- Easier reasoning about code
- Safer APIs
But immutability in Java is shallow by default.
The Trap: “Looks Immutable” but Isn’t
Consider this class:
public final class Person {
private final String name;
private final List<String> hobbies;
public Person(String name, List<String> hobbies) {
this.name = name;
this.hobbies = hobbies;
}
}
It looks immutable.
It is not.
Why?
Because List is mutable.
List<String> list = new ArrayList<>();
Person person = new Person("Alex", list);
list.add("Gaming"); // 💥 Person just changed
Even though the fields are final, the data inside them is not protected.
Defensive Copying: The Missing Piece
This is where defensive copying comes in.
Defensive copying means creating your own copy of mutable input so external changes can’t affect your object.
You must:
- Copy mutable inputs in the constructor
- Never expose mutable internal references
The Old-School Solution (Correct but Ugly)
Before modern Java, this was the safe approach:
this.hobbies = Collections.unmodifiableList(
new ArrayList<>(hobbies)
);
It works, but:
- It’s verbose
- Easy to forget
- Hard to read
- Easy to get wrong
Java 21 gives us something much better.
Enter List.copyOf()
this.hobbies = List.copyOf(hobbies);
This single line does everything you want:
- Creates an unmodifiable list
- Defensively copies the data
- Prevents external mutation
- Fails fast on nulls
- Uses optimized immutable implementations
It’s defensive copying, modernized.
Java 21’s Best Feature for Immutability: Records
If you’re on Java 21 and modeling pure data, you should almost always use a record.
Records give you:
finalclassprivate finalfields- Constructor enforcement
equals,hashCode,toStringfor free
They are designed for immutability.
The Right Way: Immutable Record with Collections
import java.util.List;
public record Person(String name, List<String> hobbies) {
public Person {
hobbies = List.copyOf(hobbies);
}
}
That’s it.
No setters.
No defensive code everywhere.
No accidental mutation.
Trying to modify it?
person.hobbies().add("Gaming");
// throws UnsupportedOperationException
Perfect!
Important: Records Are Not Deeply Immutable by Default
This is a common misconception.
Records make fields final — not their contents.
Without List.copyOf():
List<String> hobbies = new ArrayList<>();
Person p = new Person("Alex", hobbies);
hobbies.add("Gaming"); // still breaks immutability
Records give you structural immutability.
Defensive copying gives you data immutability.
You need both.
When Records Are NOT a Good Fit
Avoid records if:
- Objects have a lifecycle
- State is expected to change
- You need inheritance
- You’re working with JPA proxies
For immutable data? Records are ideal.
Final Takeaway
Java 21 finally makes immutability simple.
The modern rule of thumb:
If it’s immutable data → use
*record*If it contains collections → use*List.copyOf()*,*Set.copyOf()*,*Map.copyOf()*
Happy coding!