skip to content

Are collections from List.of / Map.of deeply immutable, and what does that mean for stored mutable objects and thread safety?

level: seniorimportance: should knowfreq 48%

answer

  1. Structure locked, contents' internals not
  2. Shallow != deep immutability
  3. Mutable element inside stays mutable
  4. Deep immutability = compose immutable pieces
  5. Immutable + immutable elements = thread-safe, no locks

basics

~20 s

List.of and Map.of collections are only shallowly immutable: you cannot add, remove, or replace elements, but a mutable element (an ArrayList, a bean) can still change internally. The collection's structure is fixed; mutable elements bring their own thread-safety hazards.

solid answer

~50 s

List.of and friends guarantee structural stability: the references the collection holds can never change, and mutating operations throw. But this is shallow, not deep; the Javadoc's word is unmodifiable, and it warns that such a collection is not necessarily immutable. If you store a reference to a mutable object, that object can still be mutated through any reference to it, including the one inside the collection. For example, List.of(new ArrayList<>(...)) prevents replacing the inner list but does nothing to stop someone calling add() on it. For deep immutability you must store only immutable elements (Strings, boxed primitives, records of immutable fields, unmodifiable collections of those). On thread safety: JEP 269 says that once constructed and safely published, these collections are safe for concurrent access. If the elements are mutable, you keep the usual concurrency hazards on those elements, even though the collection itself is fixed.

code

java · 9 lines
java
List<List<Integer>> outer = List.of(new ArrayList<>(List.of(1, 2)));

// outer.add(List.of(9));   -> UnsupportedOperationException (structure locked)
outer.get(0).add(3);         // allowed: inner ArrayList is mutable
System.out.println(outer);   // [[1, 2, 3]]

// Deep immutability: compose immutable pieces
List<List<Integer>> deep = List.of(List.of(1, 2));
// deep.get(0).add(3);       -> UnsupportedOperationException

go deeper

for a junior

Knows the collection itself can't be added to or modified.

for a middle

Understands shallow vs deep: that mutable elements inside can still change.

for a senior

Explains how to achieve deep immutability by composition and the thread-safety consequences of mutable vs immutable elements.

for a principal

Reasons about safe publication, designs immutable domain types, and sets conventions to prevent leaking mutable state through 'immutable' APIs.

## What 'immutable' really covers When people call `List.of(...)` *immutable*, they mean the collection's *structure* is fixed: it always holds the same references, in the same positions, and any attempt to change that (`add`, `set`, `remove`, `clear`) throws `UnsupportedOperationException`. This is called **shallow** or **structural** immutability. The Javadoc's own word is **unmodifiable**, and it is blunt about the gap: "An unmodifiable collection is not necessarily immutable." If all the elements are immutable, it "can be considered effectively immutable." ## Shallow vs deep - *Shallow immutability*: the container cannot change which objects it points to. - *Deep immutability*: neither the container nor any object it (transitively) contains can change. A reference is just an address pointing at an object. A `List<StringBuilder>` from `List.of(...)` permanently holds the same `StringBuilder` references — but a `StringBuilder` is itself mutable, so its *contents* can change even though the list's pointer to it cannot. ```java StringBuilder sb = new StringBuilder("hi"); List<StringBuilder> list = List.of(sb); // list.set(0, ...) -> UnsupportedOperationException (structure is locked) sb.append(" there"); // allowed! the element's own state changed System.out.println(list.get(0)); // "hi there" ``` The list never changed which object it points to, yet the observable contents changed. That is shallow immutability. ## A nested-collection example ```java List<List<Integer>> outer = List.of(new ArrayList<>(List.of(1, 2))); // outer.add(...) throws outer.get(0).add(3); // the INNER ArrayList is mutable System.out.println(outer); // [[1, 2, 3]] ``` The outer list is immutable; the inner one is not, so the whole structure effectively changed. ## Mutable elements in a Set or as Map keys `Set.of` and `Map.of` carry an extra hazard, because they find elements by `hashCode` and `equals`. The Javadoc warns that a mutable element "may cause the Set to behave inconsistently", and JEP 269 says that after a mutation affecting those methods "the behavior of the collection could become unspecified." So these need stable keys, not just a fixed structure. ## How to get deep immutability There is no flag for it — you must compose immutable pieces: 1. Store only inherently immutable elements: `String`, boxed primitives (`Integer`, `Long`…), `java.time` types, `enum`s without mutable fields, `record`s whose fields are all immutable. 2. For nested collections, store unmodifiable collections of immutable elements (`List.of(List.of(1, 2))`). 3. For your own classes, make them immutable (final fields, no setters, defensive copies of any mutable inputs, and don't leak internal references). ## Thread-safety implications This is where it matters most. *Immutable objects are inherently thread-safe*: if nothing about an object can change after construction, multiple threads can read it concurrently with no locks. JEP 269 states the rule for these collections: "Once constructed and safely published, these collection instances will be safe for concurrent access by multiple threads." - A `List.of` of immutable elements → safe to share across threads once published. - A `List.of` of *mutable* elements → the **collection** is safe (no thread can restructure it), but the **elements** are not: two threads mutating a shared inner `ArrayList` still race and need synchronization. The structural immutability gives a false sense of safety here. **Publication is still your job.** Hand the reference over through a `final` field, a `volatile`, a lock or a concurrent collection. There is a backstop in the current JDK: the factory classes keep their state in `final` fields, and JLS §17.5 says a thread that sees such an object sees the correctly constructed version of those fields, even through a data race. That is an implementation fact, not a promise in the Javadoc, and a half-built `ArrayList` shared through a data race gets no such protection. **Do not lock on one.** The factory instances are value-based: the Javadoc says they should not be used for synchronization, and that in a future release it may fail. ## Takeaway `List.of`/`Set.of`/`Map.of` lock the container, not the contents. Treat them as a building block: combine them with immutable elements to reach deep immutability and thread safety without locks; if you stuff mutable objects inside, you keep all the concurrency obligations on those objects.

  • If I do List.of(new ArrayList<>()), can I still add to that inner ArrayList?
    Yes. The outer list locks its references, but the inner ArrayList is a mutable object you can still modify; immutability is shallow.
  • Is a List.of of Strings safe to share across threads without synchronization?
    Yes, once it is safely published. Strings are immutable and the collection is structurally immutable, so concurrent reads are safe with no locks.

  • Claiming List.of makes contained objects immutable too
  • Assuming a List.of of mutable objects is automatically thread-safe to mutate
  • Thinking nested ArrayList inside List.of cannot be changed
  • Believing there's a 'deep immutable' flag on the factories

List.of, Set.of and Map.of
Java 9

Assumes JDK 27, the same at JDK 25: the factory classes read the same and the behaviour matches. The factories date from Java 9.

context