immutable: List.of vs unmodifiableList vs copyOf - null handling, views vs copies, JMH wrap/copy overhead, a Guava comparison, and the record defensive-copy trap

This commit is contained in:
2026-10-01 11:32:13 +00:00
parent 64de44fa65
commit 2eaa464bad
18 changed files with 731 additions and 0 deletions
@@ -0,0 +1,71 @@
package com.ankurm.immutable;
import java.util.ArrayList;
import java.util.List;
/**
* A record's canonical constructor does NOT defensively copy a {@code List} field for you - it
* stores exactly the reference it was handed. If the caller passes a mutable {@code ArrayList},
* the record's "immutable" field is only as immutable as whatever the caller does with their own
* reference next. This demo shows the leak on {@link LeakyOrder}, then the fix on {@link SafeOrder},
* which calls {@code List.copyOf(...)} inside a compact constructor.
*/
public final class DefensiveCopyRecordDemo {
record LeakyOrder(String id, List<String> items) {
// no compact constructor - items is stored exactly as passed in
}
record SafeOrder(String id, List<String> items) {
SafeOrder {
items = List.copyOf(items); // snapshot + reject nulls, same guarantee List.of gives you
}
}
private DefensiveCopyRecordDemo() {}
public static void main(String[] args) {
System.out.println("=== LeakyOrder: a record field that LOOKS immutable but isn't ===");
List<String> callerList = new ArrayList<>(List.of("widget", "gadget"));
LeakyOrder leaky = new LeakyOrder("ORD-1", callerList);
System.out.println("leaky.items() right after construction = " + leaky.items());
callerList.add("SNEAKY EXTRA ITEM");
System.out.println("caller mutates their OWN list reference afterwards: callerList.add(...)");
System.out.println("leaky.items() now = " + leaky.items()
+ " <- the record's field changed too, because it's the SAME list object");
System.out.println();
System.out.println("=== LeakyOrder.items() also returns the live mutable reference - callers can mutate it directly ===");
leaky.items().add("MUTATED THROUGH THE ACCESSOR");
System.out.println("leaky.items() after leaky.items().add(...) = " + leaky.items());
System.out.println();
System.out.println("=== SafeOrder: List.copyOf(...) in a compact constructor closes both holes ===");
List<String> callerList2 = new ArrayList<>(List.of("widget", "gadget"));
SafeOrder safe = new SafeOrder("ORD-2", callerList2);
System.out.println("safe.items() right after construction = " + safe.items());
callerList2.add("SNEAKY EXTRA ITEM");
System.out.println("caller mutates their OWN list reference afterwards: callerList2.add(...)");
System.out.println("safe.items() now = " + safe.items() + " <- unchanged, it's an independent copy");
System.out.println();
System.out.println("=== And the accessor's result rejects mutation too, since List.copyOf returns an immutable list ===");
try {
safe.items().add("should not be possible");
} catch (UnsupportedOperationException e) {
System.out.println("safe.items().add(...) threw UnsupportedOperationException");
}
System.out.println();
System.out.println("=== The constructor itself still rejects null elements, same as List.of ===");
try {
List<String> withNull = new ArrayList<>();
withNull.add("a");
withNull.add(null);
new SafeOrder("ORD-3", withNull);
System.out.println("new SafeOrder(..., listContainingNull) succeeded (unexpected)");
} catch (NullPointerException e) {
System.out.println("new SafeOrder(..., listContainingNull) threw NullPointerException from inside List.copyOf(...)");
}
}
}
@@ -0,0 +1,54 @@
package com.ankurm.immutable;
import com.google.common.collect.ImmutableList;
import java.util.List;
/**
* Guava's {@code ImmutableList} predates {@code List.of} by roughly a decade (Guava's collections
* shipped around 2010; {@code List.of} landed in Java 9, 2017) and most of its behaviour now
* matches the JDK's own immutable lists - this demo exists to pin the two places it still doesn't.
*/
public final class GuavaComparisonDemo {
private GuavaComparisonDemo() {}
public static void main(String[] args) {
System.out.println("=== Both reject null, same as List.of ===");
try {
ImmutableList.of("a", null, "c");
System.out.println("ImmutableList.of(\"a\", null, \"c\") succeeded (unexpected)");
} catch (NullPointerException e) {
System.out.println("ImmutableList.of(\"a\", null, \"c\") threw NullPointerException - same as List.of");
}
System.out.println();
System.out.println("=== Guava's builder tolerates a size that grows past what you declared; List.of has no builder ===");
ImmutableList<Integer> built = ImmutableList.<Integer>builder()
.add(1).add(2).add(3).add(4).add(5)
.build();
System.out.println("ImmutableList.builder() result = " + built);
System.out.println("-> java.util has no equivalent builder; you either know all elements up front for List.of(...)");
System.out.println(" or you build an ArrayList and call List.copyOf(...) at the end - this demo's RecordDemo does exactly that.");
System.out.println();
System.out.println("=== Element limit: List.of has none in practice; the old Arrays.asList(E...) varargs ceiling is long gone ===");
Integer[] many = new Integer[5000];
for (int i = 0; i < many.length; i++) many[i] = i;
List<Integer> bigListOf = List.of(many);
System.out.println("List.of(... 5000 elements ...).size() = " + bigListOf.size()
+ " (List.of(E...) switched to a varargs array long ago - the old 1-10 overloads are just JIT-friendlier for small sizes)");
System.out.println();
System.out.println("=== Guava's ImmutableList also exposes a reverse() view and asList() - conceptually close to JEP 431's reversed() ===");
ImmutableList<Integer> reversed = built.reverse();
System.out.println("built.reverse() = " + reversed + " (Guava's reverse() predates java.util's reversed() by over a decade)");
System.out.println();
System.out.println("=== Where they genuinely differ: Guava's collections are NOT in java.base, so they ship as a real dependency ===");
System.out.println("Adding Guava to a project to get ImmutableList today mostly buys you nothing List.of/List.copyOf");
System.out.println("doesn't already give you for the collection types themselves - the builder pattern above is the");
System.out.println("real remaining reason, plus ImmutableList/ImmutableMap/ImmutableSet having first-class equivalents");
System.out.println("for ImmutableMultimap, ImmutableTable and other Guava-only collection types the JDK has no analog for.");
}
}
@@ -0,0 +1,105 @@
package com.ankurm.immutable;
import com.google.common.collect.ImmutableList;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Two questions: (1) does wrapping vs copying cost anything measurable at construction time, and
* (2) does reading through an unmodifiable wrapper cost anything measurable per call, versus
* reading the backing list directly or reading an immutable copy. Source for every number quoted
* in the post: {@code output/05-jmh-raw.txt}.
*/
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2, time = 1)
@Measurement(iterations = 3, time = 1)
@Fork(2)
public class ImmutableOverheadBenchmark {
@State(Scope.Benchmark)
public static class ConstructionState {
@Param({"10", "1000"})
int size;
List<Integer> source;
@Setup(Level.Invocation)
public void setup() {
source = new ArrayList<>(size);
for (int i = 0; i < size; i++) source.add(i);
}
}
@Benchmark
public List<Integer> construct_unmodifiableListWrap(ConstructionState s) {
return Collections.unmodifiableList(s.source);
}
@Benchmark
public List<Integer> construct_listCopyOf(ConstructionState s) {
return List.copyOf(s.source);
}
@Benchmark
public ImmutableList<Integer> construct_guavaImmutableListCopyOf(ConstructionState s) {
return ImmutableList.copyOf(s.source);
}
@State(Scope.Benchmark)
public static class ReadState {
@Param({"1000"})
int size;
List<Integer> plainArrayList;
List<Integer> unmodifiableWrapper;
List<Integer> immutableCopy;
@Setup(Level.Trial)
public void setup() {
plainArrayList = new ArrayList<>(size);
for (int i = 0; i < size; i++) plainArrayList.add(i);
unmodifiableWrapper = Collections.unmodifiableList(plainArrayList);
immutableCopy = List.copyOf(plainArrayList);
}
}
@Benchmark
public int read_plainArrayList_get(ReadState s) {
int sum = 0;
for (int i = 0; i < s.size; i++) sum += s.plainArrayList.get(i);
return sum;
}
@Benchmark
public int read_unmodifiableWrapper_get(ReadState s) {
int sum = 0;
for (int i = 0; i < s.size; i++) sum += s.unmodifiableWrapper.get(i);
return sum;
}
@Benchmark
public int read_immutableCopy_get(ReadState s) {
int sum = 0;
for (int i = 0; i < s.size; i++) sum += s.immutableCopy.get(i);
return sum;
}
public static void consume(Blackhole bh, Object o) {
bh.consume(o);
}
}
@@ -0,0 +1,68 @@
package com.ankurm.immutable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* The three factory families people reach for to build a "read-only-looking" list disagree about
* {@code null} in three different ways. This demo runs all three against the same question -
* "can this list contain a null element at all" - and prints the real exception (or lack of one)
* for each, rather than describing it from memory.
*/
public final class NullHandlingDemo {
private NullHandlingDemo() {}
public static void main(String[] args) {
System.out.println("=== List.of(...) - rejects null at construction time ===");
try {
List<String> l = List.of("a", null, "c");
System.out.println("List.of(\"a\", null, \"c\") succeeded (unexpected): " + l);
} catch (NullPointerException e) {
System.out.println("List.of(\"a\", null, \"c\") threw NullPointerException");
}
System.out.println();
System.out.println("=== Arrays.asList(...) - allows null, it's just a view over the array ===");
List<String> viaAsList = Arrays.asList("a", null, "c");
System.out.println("Arrays.asList(\"a\", null, \"c\") = " + viaAsList);
System.out.println();
System.out.println("=== Collections.unmodifiableList(...) - allows whatever the backing list allows ===");
ArrayList<String> backing = new ArrayList<>();
backing.add("a");
backing.add(null);
backing.add("c");
List<String> unmodView = Collections.unmodifiableList(backing);
System.out.println("unmodifiableList over a list already containing null = " + unmodView);
System.out.println("(it has no null-check of its own - it only blocks structural writes, see below)");
System.out.println();
System.out.println("=== List.copyOf(...) - rejects null, same as List.of ===");
try {
List<String> copy = List.copyOf(viaAsList); // viaAsList contains a null
System.out.println("List.copyOf(aListContainingNull) succeeded (unexpected): " + copy);
} catch (NullPointerException e) {
System.out.println("List.copyOf(aListContainingNull) threw NullPointerException");
System.out.println("-> List.copyOf() re-validates elements, it does not just wrap and trust the source");
}
System.out.println();
System.out.println("=== Collections.unmodifiableList is a VIEW, not a copy: mutating the backing list shows through ===");
System.out.println("before: unmodView = " + unmodView);
backing.set(0, "A-CHANGED");
backing.add("d");
System.out.println("after backing.set(0,...) and backing.add(\"d\"): unmodView = " + unmodView);
System.out.println("-> the \"unmodifiable\" promise is about the VIEW's own mutator methods, not about the data being frozen");
System.out.println();
System.out.println("=== unmodifiableList's own mutators still throw, even though the backing list is mutable ===");
try {
unmodView.add("e");
} catch (UnsupportedOperationException e) {
System.out.println("unmodView.add(\"e\") threw UnsupportedOperationException");
}
}
}
@@ -0,0 +1,62 @@
package com.ankurm.immutable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The single most important distinction between the three "read-only-looking" factories:
* {@code Collections.unmodifiableList} wraps the collection you gave it and keeps watching it,
* while {@code List.copyOf} takes a snapshot and never looks at the source again. Both refuse
* writes through themselves; only one of them actually freezes the data.
*/
public final class ViewsVsCopiesDemo {
private ViewsVsCopiesDemo() {}
public static void main(String[] args) {
System.out.println("=== unmodifiableList is a VIEW: changes to the backing list show through ===");
ArrayList<String> backing = new ArrayList<>(List.of("a", "b", "c"));
List<String> view = Collections.unmodifiableList(backing);
System.out.println("backing = " + backing);
System.out.println("view = " + view);
backing.add("d");
System.out.println("after backing.add(\"d\"):");
System.out.println("backing = " + backing);
System.out.println("view = " + view + " <- changed, with no code touching 'view' directly");
System.out.println();
System.out.println("=== List.copyOf is a SNAPSHOT: changes to the source do NOT show through ===");
ArrayList<String> source = new ArrayList<>(List.of("x", "y", "z"));
List<String> copy = List.copyOf(source);
System.out.println("source = " + source);
System.out.println("copy = " + copy);
source.add("w");
System.out.println("after source.add(\"w\"):");
System.out.println("source = " + source);
System.out.println("copy = " + copy + " <- unchanged, it was a real copy at the moment copyOf() ran");
System.out.println();
System.out.println("=== List.copyOf has a documented optimization: copying an already-immutable list is a no-op ===");
List<String> alreadyImmutable = List.of("p", "q");
List<String> copyOfImmutable = List.copyOf(alreadyImmutable);
System.out.println("List.copyOf(List.of(...)) returns the SAME instance: "
+ (alreadyImmutable == copyOfImmutable));
List<String> mutableSource = new ArrayList<>(List.of("p", "q"));
List<String> copyOfMutable = List.copyOf(mutableSource);
System.out.println("List.copyOf(new ArrayList<>(...)) returns a DIFFERENT instance: "
+ (mutableSource != copyOfMutable));
System.out.println();
System.out.println("=== Map and Set follow the same pattern as List ===");
Map<String, Integer> mutableMap = new HashMap<>();
mutableMap.put("one", 1);
Map<String, Integer> unmodMapView = Collections.unmodifiableMap(mutableMap);
Map<String, Integer> mapCopy = Map.copyOf(mutableMap);
mutableMap.put("two", 2);
System.out.println("unmodMapView after mutating backing map = " + unmodMapView + " (view: changed)");
System.out.println("mapCopy after mutating the ORIGINAL map = " + mapCopy + " (copy: unchanged)");
}
}
@@ -0,0 +1,108 @@
package com.ankurm.immutable;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ImmutableCollectionsTest {
@Test
void listOfRejectsNull() {
assertThrows(NullPointerException.class, () -> List.of("a", null, "c"));
}
@Test
void arraysAsListAllowsNullBecauseItIsJustAnArrayView() {
List<String> l = Arrays.asList("a", null, "c");
assertEquals(null, l.get(1));
}
@Test
void unmodifiableListHasNoNullCheckOfItsOwn() {
ArrayList<String> backing = new ArrayList<>();
backing.add("a");
backing.add(null);
List<String> view = Collections.unmodifiableList(backing);
assertEquals(null, view.get(1));
}
@Test
void listCopyOfRevalidatesAndRejectsNull() {
List<String> withNull = Arrays.asList("a", null, "c");
assertThrows(NullPointerException.class, () -> List.copyOf(withNull));
}
@Test
void unmodifiableListIsALiveViewOverTheBackingList() {
ArrayList<String> backing = new ArrayList<>(List.of("a", "b"));
List<String> view = Collections.unmodifiableList(backing);
backing.add("c");
assertEquals(List.of("a", "b", "c"), view, "the view must see the backing list's mutation");
}
@Test
void listCopyOfIsAnIndependentSnapshot() {
ArrayList<String> source = new ArrayList<>(List.of("x", "y"));
List<String> copy = List.copyOf(source);
source.add("z");
assertEquals(List.of("x", "y"), copy, "the copy must NOT see the source's later mutation");
}
@Test
void listCopyOfAnAlreadyImmutableListIsANoOp() {
List<String> imm = List.of("p", "q");
assertSame(imm, List.copyOf(imm), "List.copyOf must return the same instance for an already-immutable source");
}
@Test
void listCopyOfAMutableListAllocatesANewInstance() {
List<String> mutable = new ArrayList<>(List.of("p", "q"));
assertFalse(mutable == List.copyOf(mutable));
}
@Test
void bothUnmodifiableViewAndImmutableCopyRejectDirectMutation() {
List<String> view = Collections.unmodifiableList(new ArrayList<>(List.of("a")));
List<String> copy = List.copyOf(List.of("a"));
assertThrows(UnsupportedOperationException.class, () -> view.add("b"));
assertThrows(UnsupportedOperationException.class, () -> copy.add("b"));
}
@Test
void guavaImmutableListAlsoRejectsNull() {
assertThrows(NullPointerException.class, () -> ImmutableList.of("a", null));
}
@Test
void recordWithoutCompactConstructorLeaksTheBackingList() {
List<String> callerList = new ArrayList<>(List.of("a", "b"));
record LeakyOrder(String id, List<String> items) {}
LeakyOrder leaky = new LeakyOrder("ORD-1", callerList);
callerList.add("LEAKED");
assertTrue(leaky.items().contains("LEAKED"), "without a defensive copy the record sees the caller's later mutation");
}
@Test
void recordWithListCopyOfInCompactConstructorIsSafe() {
List<String> callerList = new ArrayList<>(List.of("a", "b"));
record SafeOrder(String id, List<String> items) {
SafeOrder {
items = List.copyOf(items);
}
}
SafeOrder safe = new SafeOrder("ORD-2", callerList);
callerList.add("SHOULD NOT LEAK");
assertFalse(safe.items().contains("SHOULD NOT LEAK"), "List.copyOf in the compact constructor must snapshot");
assertThrows(UnsupportedOperationException.class, () -> safe.items().add("x"));
}
}