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. String, Integer, LocalDate, BigDecimal and the collections made by List.of are all immutable: methods that look like changes, such as toUpperCase or plusDays, return a new object.

Marking fields final is not enough, because a final field can point to an object that changes. A class is immutable only when all of these hold:

The recipe for an immutable class
RuleWhy
All fields private finalNothing can reassign them
No setters or other methods that change fieldsThe obvious part
The class is final (or a record)A subclass could add mutable state or override methods
Mutable inputs are copied in the constructorThe caller still holds a reference to what it passed in
Mutable fields are never handed out directlyA getter would give callers a way in
this does not escape the constructorOther code could see the object before its fields are set
What immutability gives you
BenefitBecause
Thread safety without locksNothing changes, so there is nothing to synchronize
Safe map keys and set elementsThe hash code cannot change after insertion
Free sharing and cachingNo defensive copies needed; the Integer and string pools rely on this
Easier reasoningA 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 at the end shows the same problem with a different mutable type.

Java
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:

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.
  • Team copies the input with List.copyOf, which also makes it unmodifiable. Because the stored list cannot be changed, the getter can return it directly without another copy.
  • "Changing" an immutable object means making a new one: withMember returned a team of three and left the original two-member team alone.
  • java.util.Date is mutable, so a Date field needs the same copying. Better, use the immutable java.time types; see date 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 and the limit of all of them: they protect the list, not the objects in it.

Java
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:

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)]
  • Collections.unmodifiableList 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.
  • List.copyOf (Java 10) makes an independent copy that stays as it was. When the argument is already an immutable list from List.of or copyOf, it returns the same object, so copying defensively costs nothing in that case. A view is not immutable, so it was copied.
  • List.of, Set.of, Map.of and the copyOf methods reject null elements.
  • Immutability is shallow: an immutable list of StringBuilders still allowed one builder to be changed. A deeply immutable object contains only immutable objects. See immutable 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.

Java
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:

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
  • plus returned a new Money of 15.50 and left a at 12.50. Two records with the same components are equal, which is what a value should be.
  • 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 Event constructor replaces the tags list with List.copyOf(tags); without that, the caller could change the event's tags later.
  • withDate 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.

Sharing immutable state between threads

Immutable objects make a simple and safe concurrency pattern possible: keep the current state in an AtomicReference, and update it by building a new immutable object and swapping it in. The program runs four writer threads that each add 250 flags to a shared configuration, while a reader takes snapshots without any locking.

Java
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:

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. updateAndGet 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.
  • The reader never saw a snapshot smaller than an earlier one, and it never needed a lock: each Config it read was complete and could not change while it was being used.
  • 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 += and with a StringBuilder. Each timing is the best of 3 runs on a 2-CPU machine; treat it as a rough comparison.

Java
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:

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 Point 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.
  • String is immutable, so s += "x" copies the whole string each time, which makes the loop quadratic: 20,000 additions copied about 200 million characters. StringBuilder is the mutable companion made for building strings. The same "mutable builder, immutable result" pattern is used by Stream.toList() and many APIs.

Checklist

Making a class immutable
SituationDo
A new value classWrite a record
A list, set or map fieldList.copyOf, Set.copyOf or Map.copyOf in the constructor
An array fieldclone() in the constructor and in the getter, or store a List instead
Dates and timesjava.time types, which are immutable
Changing a valueA method that returns a new object (withX, plus)
Building complex values step by stepA mutable builder that produces an immutable result
Shared state across threadsAn immutable snapshot in an AtomicReference or a volatile field

Related pages: the final keyword, records and access modifiers.