Quick revision
The short answer
subList(0, 100) is a view that keeps a reference to the whole backing list, so as long as the cache holds the view, the huge list and every object in it stay reachable and cannot be garbage collected. The fix is to store a copy, List.copyOf(list.subList(0, 100)), which keeps only the 100 elements; better still, fetch only 100 rows from the database with a limit. The same retention happens with other views, such as keySet, values or Collections.unmodifiableList.
What to remember
In this answer, we saw that subList(0, 100) is a view whose root reference keeps the entire backing list and all its elements reachable, so a cached view retains the million rows. A heap dump shows it as a tiny SubList with a huge retained size. Storing List.copyOf(list.subList(0, 100)) frees the source, and fetching only 100 rows with an ordered LIMIT removes the waste altogether. Other views, such as keySet, values and unmodifiableList, retain their sources the same way.
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.
subList(0, 100) is a view that keeps a reference to the whole backing list, so as long as the cache holds the view, the huge list and every object in it stay reachable and cannot be garbage collected. The fix is to store a copy, List.copyOf(list.subList(0, 100)), which keeps only the 100 elements; better still, fetch only 100 rows from the database with a limit. The same retention happens with other views, such as keySet, values or Collections.unmodifiableList.
Why this question is asked
Memory leaks in Java are rarely about forgotten free calls; they are about references we did not know we kept. This scenario is a textbook example, and it shows up in real services as a cache that should be small but holds gigabytes. Interviewers ask it to see whether we understand reachability and views, and whether we fix the root cause rather than the symptom. In this answer, we will recap how garbage collection decides what to keep, see what the view holds on to, prove it with a heap dump, and then fix it twice: with a copy and with a smaller query.
1A Quick Recap of Reachability
The garbage collector frees objects that are no longer reachable: objects that cannot be reached by following references from GC roots, such as live threads' stacks and static fields. A cache stored in a static field or in a Spring singleton is reachable for the life of the application, and so is everything that the cached values reference, directly or indirectly.
So the question for any cache is not how big the value looks, but how much the value can reach. A small-looking object that holds one reference to a big structure keeps that whole structure alive.
2What subList(0, 100) Really Holds
subList does not copy elements. ArrayList's sublist view holds a reference to the backing list (its root), an offset and a size. Through the root it can reach the backing array, and through the array every element: all of the rows loaded from the database, not just the first 100.
- Cache (singleton)reachable for the life of the app
- SubList viewoffset 0, size 100, root -> backing list
- ArrayListsize 1,000,000
- Object[] elementData1,000,000 references
- Product entitiesall 1,000,000 objects and their fields
5 layers, from the top down. Step through them one at a time.
Everything below the cache entry is reachable, so nothing can be collected.
Notice the line all = null. People sometimes expect it to free the list, but it only clears one local reference. The view still points at the list, and the cache points at the view, so the whole chain stays reachable.
3Confirming It With a Heap Dump
We confirm the theory before changing code. A heap dump, taken with jcmd <pid> GC.heap_dump /tmp/app.hprof, can be opened in a tool such as Eclipse MAT. Its dominator tree shows, for each object, the memory that would be freed if that object became unreachable, called its retained size.
The tell-tale line is a SubList with a small size but a huge retained size. That is exactly the gap between what the cache was meant to keep and what it keeps.
4Fix 1: Store a Copy, Not a View
A copy owns its own array of exactly the elements we want, with no reference to the original list. Once the method returns, nothing references the big list, and the next garbage collection frees it.
List.copyOf also makes the cached value immutable, which is what we want for data shared between requests, and it rejects null elements. If the cached list must be modifiable, new ArrayList<>(all.subList(0, 100)) works the same way for memory. Note that the copy holds the same 100 Product objects, not copies of them, which is fine as long as those objects do not themselves reference the big list.
5Fix 2: Do Not Load the Million Rows at All
The copy fixes the leak, but the service still loads a million rows, maps them into entities and throws away 999,900 of them on every cache refresh. That wastes database time, network transfer and a large temporary allocation. The real fix is to ask the database for 100 rows. With Spring Data JPA that can be a derived query or a Pageable; in plain JPA it is setMaxResults; in SQL it is LIMIT or FETCH FIRST.
- Heap dump: small view, huge retained sizedominator tree shows
SubList - Can the query return fewer rows?YesAdd LIMIT and ORDER BYNoCopy the part we keep
- Store List.copyOf(...)no reference to the source
- Re-check retained sizeshould match 100 entities
4 steps in order. Play them, or step through them one at a time.
Always pair a limit with an explicit order: without ORDER BY, the database is free to return any 100 rows, and the first 100 of the old list may have depended on an accidental order.
6The Same Trap With Other Views
subList is not the only view. map.keySet(), map.values() and map.entrySet() are views that reference the whole map. Collections.unmodifiableList(list) is a read-only view that keeps the original list alive and also reflects later changes to it. Arrays.asList(array) is a view over the array. Caching any of them keeps the whole source reachable. The rule is the same for all: if a value is meant to outlive its source, store a copy such as List.copyOf, Set.copyOf or Map.copyOf, not a view.
7Follow-up questions
Would a WeakReference or a cache with eviction solve this?
It would hide it. Eviction limits how many entries stay, but each entry would still retain its whole source list, so a single entry can still hold hundreds of megabytes. Weak references would let the data disappear unpredictably. The correct fix is to cache only the data we mean to keep.
Did String.substring have the same problem?
It used to. Before Java 7 update 6, substring shared the original string's character array, so a short substring of a huge string kept the whole array alive. Since then substring copies the characters. subList was never changed, because write-through is part of its contract.
How do we stop this from happening again?
We make caches store copies by design, for example by having the cache wrapper call List.copyOf on put, and we prefer queries that fetch only what we need. A code review rule that flags subList, keySet or values results stored in fields or caches catches most new cases.
8Conclusion
In this answer, we saw that subList(0, 100) is a view whose root reference keeps the entire backing list and all its elements reachable, so a cached view retains the million rows. A heap dump shows it as a tiny SubList with a huge retained size. Storing List.copyOf(list.subList(0, 100)) frees the source, and fetching only 100 rows with an ordered LIMIT removes the waste altogether. Other views, such as keySet, values and unmodifiableList, retain their sources the same way.
Open with
The memory does not go down because subList does not copy anything. It returns a view that holds a reference to the backing list, plus an offset and a size.
Then, if they want more
So the cache holds the view, the view holds the million-element list, and the list holds every entity. They are all reachable from the cache, so the garbage collector cannot free any of them, even if the code nulls out its own variable.
In a heap dump this shows as an ArrayList SubList of size 100 with a retained size of hundreds of megabytes. The immediate fix is to cache a copy: List.copyOf of list.subList(0, 100). The copy has its own array of a hundred references and no link to the source, so the big list becomes garbage when the method returns.
It is also immutable, which suits a shared cache, though it rejects nulls. The better fix is to not load a million rows to keep a hundred. I would change the query to fetch a hundred, with a Spring Data method like findTop100ByCategoryOrderByRank, or a PageRequest, which becomes LIMIT 100 with an explicit ORDER BY so the result is deterministic.
That also saves database time, network and allocation on every refresh. The same trap exists with any view: keySet and values of a map, Collections.unmodifiableList, and Arrays.asList all keep their source alive, so anything stored long-term should be a copy.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 7
- 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 Collections Framework, overview, java.util, package 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 cache stores list.subList(0, 100) of a huge list loaded from the database to keep only...": https://scrivio-interview-library.netlify.app/java/lists/517cee3aaa/