Quick revision
The short answer
The copies happen because the getter copies a mutable internal list on every call. Instead, we copy once in the constructor into an immutable list with List.copyOf and return that list directly, which is just as safe and costs nothing on reads; List.copyOf even returns the same instance when the input is already immutable. An unmodifiable view is only safe if the owner never changes the backing list, and for some callers a stream or forEach method avoids exposing the collection at all. We measure before and after, because escape analysis may already remove some copies.
What to remember
In this answer, we saw that the getter allocated because it copied a mutable internal list on every call, although the list never changed. Copying once at construction with List.copyOf and returning that immutable list directly keeps the same safety and removes the per-read cost, and List.copyOf even skips the copy when the input is already immutable. An unmodifiable view is cheaper to create but only safe if the owner never changes the backing list, and stream, forEach or aggregate methods can avoid exposing the collection. We confirm the fix with allocation profiling, because escape analysis may already remove some copies.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The copies happen because the getter copies a mutable internal list on every call. Instead, we copy once in the constructor into an immutable list with List.copyOf and return that list directly, which is just as safe and costs nothing on reads; List.copyOf even returns the same instance when the input is already immutable. An unmodifiable view is only safe if the owner never changes the backing list, and for some callers a stream or forEach method avoids exposing the collection at all. We measure before and after, because escape analysis may already remove some copies.
Why this question is asked
Defensive copying is good advice that turns into a performance problem when it is applied in the wrong place. A getter that copies a 10,000-element list for every call, called a few thousand times per second, allocates hundreds of megabytes per second and keeps the garbage collector busy. Interviewers ask this to see whether we can keep the safety while removing the waste, and whether we understand what each collection method really does. In this answer, we will look at the current code and why it allocates, fix it by moving the copy to construction, compare views with copies, look at stream and forEach alternatives, and finish with how to measure.
1A Quick Recap: Why the Getter Copies
A defensive copy is a copy we make so that code outside our object cannot change our internal state. The original reason for the getter's copy is sound: the object keeps a mutable ArrayList, and returning it directly would let any caller add or remove items. So each call returns new ArrayList<>(items), and each copy allocates a new array as large as the list.
Notice that the internal list never changes after construction. The object is immutable in practice, yet it pays for a copy on every read, because its internal list is of a mutable type.
2Fix: Copy Once Into an Immutable List
If the internal list cannot be modified by anyone, including our own class, then returning it is safe. List.copyOf creates exactly such a list: an unmodifiable copy whose add, remove and set methods throw UnsupportedOperationException. We copy once, when the object is created, and the getter returns the same list every time.
The safety is the same as before: callers cannot change the order's items. The cost moved from every read to a single copy at construction, which for a hot getter is a huge saving. If the type is a record, this is the compact constructor items = List.copyOf(items).
3When List.copyOf Does Not Copy at All
List.copyOf has a useful shortcut. If the argument is already an unmodifiable list created by List.of or List.copyOf, it returns that same instance, because a list that can never change needs no protection. So when objects are built from each other, for example a new Order created from an old order's items, no copying happens at any step.
| Approach | Allocation per read | Safe? |
|---|---|---|
return new ArrayList<>(items) | full copy | yes |
copy once with List.copyOf, return it | none | yes |
return Collections.unmodifiableList(items) | small wrapper | only if the owner never changes items |
expose stream() or forEach(...) | small or none | yes; callers cannot keep a list |
| return items directly (mutable) | none | no |
The third line matters: an unmodifiable view is not trusted, because its backing list may change. The last line is a detail worth knowing: Stream.toList() returns an unmodifiable list that may contain nulls, and List.copyOf rejects nulls, so it must check and copy; this is current JDK behaviour, so check your version if it matters.
4Views Versus Copies
Collections.unmodifiableList(items) returns a view: a thin wrapper that forbids changes through itself but reads through to the original list. Creating it is cheap, a small object rather than a full copy. But it is only safe if nobody changes the backing list. If our class itself adds to items later, callers holding the view see the change, and a caller iterating it while we add gets a ConcurrentModificationException.
So views suit a different design: an object that does change its own list, but wants callers to only read it. For our immutable domain object, the copy at construction is simpler and stronger, and if we return a view we must document that it is a view.
5Exposing Behaviour Instead of the Collection
Sometimes callers do not need a List at all; they want to loop over items or compute a total. Then the object can offer that directly, which hides the collection type and lets us change the representation later.
A method like total() is often the best fix of all, because it removes a loop that every caller was writing. But this changes the API, so it suits code we own end to end more than a widely shared library type.
6Measuring Before and After
Before changing anything, we confirm the allocation source with Java Flight Recorder or async-profiler in allocation mode, which show bytes allocated per stack trace, and after the change we check that the allocation rate and GC time drop under the same load. For a focused comparison, a JMH benchmark with -prof gc reports bytes allocated per operation.
Measurement matters because the JVM may already remove some copies. Escape analysis lets the JIT skip allocating objects that never leave a method, so a small copy consumed locally might cost nothing. In practice it rarely helps here, because a large list's backing array is too big to be eliminated and the copy is returned to the caller, so it escapes. But only a measurement tells us, and it also tells us when to stop: once the getter is no longer in the profile, we are done.
7Follow-up questions
Is List.copyOf safe for lists of mutable objects?
It protects the list's structure, so nobody can add or remove items, but the elements themselves are shared. If LineItem were mutable, callers could still change an item's fields. For a truly immutable order, the elements must be immutable too, for example records with immutable fields.
Why not cache the copy in a field the first time the getter is called?
Because it adds complexity and thread-safety questions without any benefit over copying in the constructor. Lazy caching makes sense when the copy is expensive and rarely needed; here the list exists from the start, so the constructor is the natural place.
What if the class must keep changing its list internally?
Then we have a mutable object, and we choose between returning an unmodifiable view, documented as live, or returning a snapshot copy. A good compromise is copy-on-write: each change builds a new immutable list and replaces the field, so readers always get a stable list without copying on read. CopyOnWriteArrayList works the same way for lists that are read far more often than they are changed.
8Conclusion
In this answer, we saw that the getter allocated because it copied a mutable internal list on every call, although the list never changed. Copying once at construction with List.copyOf and returning that immutable list directly keeps the same safety and removes the per-read cost, and List.copyOf even skips the copy when the input is already immutable. An unmodifiable view is cheaper to create but only safe if the owner never changes the backing list, and stream, forEach or aggregate methods can avoid exposing the collection. We confirm the fix with allocation profiling, because escape analysis may already remove some copies.
Open with
The getter is paying for a defensive copy on every read, even though the internal list never changes after construction, so I would move the copy to the constructor.
Then, if they want more
If the object stores List.copyOf of its input, the stored list is unmodifiable, so the getter can return it directly: callers still cannot add or remove items, but reads allocate nothing.
A nice property is that List.copyOf returns the same instance when its input was created by List.of or List.copyOf, so objects built from each other do not copy at all, while a mutable list or an unmodifiable view gets copied because it could still change.
I would not just return Collections.unmodifiableList, because a view reads through to the backing list and is only safe if the owner never modifies it; if it does, callers see the change and can get ConcurrentModificationException.
Where callers only iterate or sum the items, I might also offer a stream, a forEach method, or better a total method, which avoids exposing the list at all.
Before and after the change, I would measure the allocation with JFR or async-profiler and compare GC time under the same load, because escape analysis can sometimes remove copies, though large lists returned to callers usually escape.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A profiler shows heavy allocation from defensive copies of large lists in getters of a...": https://scrivio-interview-library.netlify.app/java/immutability/e01aa13796/