Immutability in Java
An immutable object cannot change after it is created. That one property removes whole classes of bugs: immutable objects can be shared between threads without locks, used safely as map keys, and passed to any code without fear that it will change them. This page explains the recipe for an immutable class and why final alone is not enough, then shows defensive copies, unmodifiable views versus copies, records, sharing across threads, and what immutability costs.
Contents
What makes a class immutable
An object is immutable when no code, anywhere, can change its observable state after the constructor finishes. StringIntegerLocalDateBigDecimalList.oftoUpperCaseplusDays
Marking fields final
| Rule | Why |
|---|---|
All fields private final | Nothing can reassign them |
| No setters or other methods that change fields | The obvious part |
The class is final | A subclass could add mutable state or override methods |
| Mutable inputs are copied in the constructor | The caller still holds a reference to what it passed in |
| Mutable fields are never handed out directly | A getter would give callers a way in |
this | Other code could see the object before its fields are set |
| Benefit | Because |
|---|---|
| Thread safety without locks | Nothing changes, so there is nothing to synchronize |
| Safe map keys and set elements | The hash code cannot change after insertion |
| Free sharing and caching | No defensive copies needed; the Integer |
| Easier reasoning | A value checked in the constructor stays valid forever |
Final is not enough: leaking mutable state
The program compares two team classes. Both have only final fields and no setters, so both look immutable. One keeps the list it was given and returns it from its getter; the other copies the list. A shared Date
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class LeakyVsSafe {
// Looks immutable (final fields, no setters) but is not
static final class LeakyTeam {
private final List<String> members;
LeakyTeam(List<String> members) {
this.members = members; // keeps the caller's list
}
List<String> members() {
return members; // hands out the internal list
}
}
// Truly immutable
static final class Team {
private final List<String> members;
Team(List<String> members) {
this.members = List.copyOf(members); // defensive copy in
}
List<String> members() {
return members; // already unmodifiable: safe to share
}
Team withMember(String name) { // "changing" returns a new object
List<String> next = new ArrayList<>(members);
next.add(name);
return new Team(next);
}
}
public static void main(String[] args) {
List<String> input = new ArrayList<>(List.of("ann", "bob"));
LeakyTeam leaky = new LeakyTeam(input);
input.add("mallory"); // caller changes its own list
leaky.members().add("eve"); // or any caller changes the getter's result
System.out.println("leaky team: " + leaky.members());
Team team = new Team(List.of("ann", "bob"));
try {
team.members().add("eve");
} catch (UnsupportedOperationException e) {
System.out.println("safe team rejects add: UnsupportedOperationException");
}
Team bigger = team.withMember("cy");
System.out.println("original: " + team.members() + ", new: " + bigger.members());
// Mutable field types like Date need copying too
Date d = new Date(0);
Date alias = d;
alias.setTime(86400000L);
System.out.println("Date shared by reference changed: " + d.toInstant());
}
}
Output:
leaky team: [ann, bob, mallory, eve]
safe team rejects add: UnsupportedOperationException
original: [ann, bob], new: [ann, bob, cy]
Date shared by reference changed: 1970-01-02T00:00:00Z
- The leaky team was changed twice from outside: by the caller adding "mallory" to the list it had passed in, and through the getter, which handed out the internal list. Neither needed a setter.
copies the input withTeam , which also makes it unmodifiable. Because the stored list cannot be changed, the getter can return it directly without another copy.List.copyOf- "Changing" an immutable object means making a new one:
returned a team of three and left the original two-member team alone.withMember is mutable, so ajava.util.Date field needs the same copying. Better, use the immutableDate types; seejava.timedate and time .
Unmodifiable views, immutable copies and shallow immutability
Java has two ways to get a list that callers cannot change, and they behave differently. The program creates both from the same source list, then changes the source. It also shows two details of List.copyOf
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ViewsAndCopies {
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(source); // read-only window
List<String> copy = List.copyOf(source); // independent snapshot
source.add("c");
System.out.println("source: " + source);
System.out.println("unmodifiable view: " + view + " (sees the change)");
System.out.println("List.copyOf: " + copy + " (does not)");
// copyOf of a list that is already unmodifiable returns the same object
List<String> fixed = List.of("x", "y");
System.out.println("copyOf(List.of(...)) same object: " + (List.copyOf(fixed) == fixed));
System.out.println("copyOf(view) same object: " + (List.copyOf(view) == view));
// Immutable collections refuse null
try {
List.of("a", null);
} catch (NullPointerException e) {
System.out.println("List.of with null: NullPointerException");
}
// Shallow: an unmodifiable list of mutable objects can still change inside
List<StringBuilder> builders = List.of(new StringBuilder("draft"));
builders.get(0).append(" (edited)");
System.out.println("List.of(StringBuilder) after append: " + builders);
}
}
Output:
source: [a, b, c]
unmodifiable view: [a, b, c] (sees the change)
List.copyOf: [a, b] (does not)
copyOf(List.of(...)) same object: true
copyOf(view) same object: false
List.of with null: NullPointerException
List.of(StringBuilder) after append: [draft (edited)]
is a view: it blocks changes made through it, but it shows changes made to the source, so it printed "c". It is not immutable; it is read-only.Collections.unmodifiableList (Java 10) makes an independent copy that stays as it was. When the argument is already an immutable list fromList.copyOf orList.of , it returns the same object, so copying defensively costs nothing in that case. A view is not immutable, so it was copied.copyOf ,List.of ,Set.of and theMap.of methods rejectcopyOf elements.null- Immutability is shallow: an immutable list of
s still allowed one builder to be changed. A deeply immutable object contains only immutable objects. SeeStringBuilderimmutable collections for more.
Records and with-methods
A record is the shortest way to write an immutable value class: its fields are private and final, it has no setters, and it is implicitly final. The program uses a money record that validates itself, and an event record with a list component and a "with" method that returns a modified copy.
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
public class RecordsAndWithers {
// A record: final fields, accessors, equals, hashCode and toString generated
record Money(long cents, String currency) {
Money { // compact constructor: validate
if (cents < 0) {
throw new IllegalArgumentException("negative amount");
}
Objects.requireNonNull(currency);
}
Money plus(Money other) {
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException("currency mismatch");
}
return new Money(cents + other.cents, currency);
}
}
record Event(String name, LocalDate date, List<String> tags) {
Event {
tags = List.copyOf(tags); // a record is only as immutable as its components
}
Event withDate(LocalDate newDate) {
return new Event(name, newDate, tags);
}
}
public static void main(String[] args) {
Money a = new Money(1250, "EUR");
Money b = a.plus(new Money(300, "EUR"));
System.out.println(a + " + 3.00 = " + b + ", a unchanged");
System.out.println("equal by value: " + new Money(5, "USD").equals(new Money(5, "USD")));
try {
new Money(-1, "USD");
} catch (IllegalArgumentException e) {
System.out.println("validation: " + e.getMessage());
}
Event launch = new Event("launch", LocalDate.of(2026, 12, 1), List.of("product"));
Event moved = launch.withDate(LocalDate.of(2027, 1, 15));
System.out.println(launch.date() + " -> " + moved.date());
}
}
Output:
Money[cents=1250, currency=EUR] + 3.00 = Money[cents=1550, currency=EUR], a unchanged
equal by value: true
validation: negative amount
2026-12-01 -> 2027-01-15
returned a newplus of 15.50 and leftMoney at 12.50. Two records with the same components are equal, which is what a value should be.a- The compact constructor checks the arguments, so a negative amount can never exist. Validation in the constructor of an immutable class runs once and holds forever.
- A record is only as immutable as its components. The
constructor replaces theEvent list withtags ; without that, the caller could change the event's tags later.List.copyOf(tags) is a with-method: a method that returns a copy with one component changed. Records do not generate with-methods yet; a JEP for "derived record creation" has been proposed but is not part of Java 21.withDate
Sharing immutable state between threads
Immutable objects make a simple and safe concurrency pattern possible: keep the current state in an AtomicReference
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public class SharingAcrossThreads {
// An immutable snapshot of configuration
record Config(int timeoutMs, Map<String, String> flags) {
Config {
flags = Map.copyOf(flags);
}
Config withFlag(String key, String value) {
Map<String, String> next = new HashMap<>(flags);
next.put(key, value);
return new Config(timeoutMs, next);
}
}
public static void main(String[] args) throws InterruptedException {
AtomicReference<Config> current = new AtomicReference<>(new Config(500, Map.of()));
// 4 threads each add 250 flags; every update builds a new Config and swaps it in
List<Thread> writers = new ArrayList<>();
for (int t = 0; t < 4; t++) {
int id = t;
writers.add(Thread.ofPlatform().start(() -> {
for (int i = 0; i < 250; i++) {
String key = "t" + id + "-" + i;
current.updateAndGet(c -> c.withFlag(key, "on"));
}
}));
}
// A reader takes snapshots without any lock while the writers run
int reads = 0;
int previous = 0;
boolean shrank = false;
while (writers.stream().anyMatch(Thread::isAlive)) {
Config snapshot = current.get();
int size = snapshot.flags().size();
shrank |= size < previous; // a lost update would make it shrink
previous = size;
reads++;
}
for (Thread w : writers) {
w.join();
}
System.out.println("reader took " + (reads > 0 ? "many" : "no")
+ " lock-free snapshots; any snapshot smaller than an earlier one: " + shrank);
System.out.println("flags after all updates: " + current.get().flags().size());
}
}
Output:
reader took many lock-free snapshots; any snapshot smaller than an earlier one: false
flags after all updates: 1000
- All 1,000 updates survived: none was lost, although four threads updated concurrently.
applies the function to the current value and stores the result only if no other thread changed the reference in the meantime; otherwise it retries with the newer value.updateAndGet - The reader never saw a snapshot smaller than an earlier one, and it never needed a lock: each
it read was complete and could not change while it was being used.Config - The update function may run more than once when threads collide, so it must have no side effects. This copy-on-write pattern suits state that is read often and written rarely; with many writers, the repeated copying becomes expensive. See
atomic classes .
What immutability costs
Every change to an immutable object allocates a new one. The program moves a point 50 million times as an immutable record and as a mutable object, then builds a 20,000-character string with +=StringBuilder
public class CostOfChange {
record Point(int x, int y) {
Point moveBy(int dx, int dy) {
return new Point(x + dx, y + dy); // a new object for every move
}
}
static final class MutablePoint {
int x;
int y;
void moveBy(int dx, int dy) {
x += dx;
y += dy;
}
}
interface Job {
long run();
}
static void time(String name, Job job) {
long best = Long.MAX_VALUE;
long result = 0;
for (int i = 0; i < 3; i++) {
long t = System.nanoTime();
result = job.run();
best = Math.min(best, System.nanoTime() - t);
}
System.out.printf("%-34s %,4d ms (result %d)%n", name, best / 1000000, result);
}
public static void main(String[] args) {
int n = 50000000;
time("immutable record, local only", () -> {
Point p = new Point(0, 0);
for (int i = 0; i < n; i++) {
p = p.moveBy(1, 2);
}
return p.x() + p.y();
});
time("mutable object", () -> {
MutablePoint p = new MutablePoint();
for (int i = 0; i < n; i++) {
p.moveBy(1, 2);
}
return p.x + p.y;
});
// String is immutable, so += in a loop copies the whole string each time
time("String += 20,000 times", () -> {
String s = "";
for (int i = 0; i < 20000; i++) {
s += "x";
}
return s.length();
});
time("StringBuilder 20,000 appends", () -> {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 20000; i++) {
sb.append("x");
}
return sb.length();
});
}
}
Output:
immutable record, local only 207 ms (result 150000000)
mutable object 0 ms (result 150000000)
String += 20,000 times 26 ms (result 20000)
StringBuilder 20,000 appends 0 ms (result 20000)
- The record version allocated a new
per move and was far slower than updating two fields in place; the mutable loop was simple enough for the JIT compiler to reduce it to almost nothing, which a loop that allocates cannot match. Short-lived objects are cheap in Java, but not free. For most code the difference is irrelevant; in tight numeric loops, keep the mutable state local to the method and expose an immutable result.Point is immutable, soString copies the whole string each time, which makes the loop quadratic: 20,000 additions copied about 200 million characters.s += "x" is the mutable companion made for building strings. The same "mutable builder, immutable result" pattern is used byStringBuilder and many APIs.Stream.toList()
Checklist
| Situation | Do |
|---|---|
| A new value class | Write a record |
| A list, set or map field | List.copyOfSet.copyOfMap.copyOf |
| An array field | clone()List |
| Dates and times | java.time |
| Changing a value | A method that returns a new object (withXplus |
| Building complex values step by step | A mutable builder that produces an immutable result |
| Shared state across threads | An immutable snapshot in an AtomicReferencevolatile |
Related pages: