Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the List subList() method prevent garbage collection of the rest of the list?

I'm curious to find out how the latest JVMs would handle garbage collecting memory reserved by the following method.

public List<Player> getHallOfFame() {
  ArrayList<Player> listToSort = new ArrayList<Player>(map.values());
  Collections.sort(listToSort, comparator);

  return listToSort.subList(0, 5);
}

At worst I can imagine the JVM keeping the entire contents of listToSort in memory as long as there remain references to the sublist. Does anyone know if that is actually the case? I'm particularly interested in links that can prove this one way or the other for specific JVMs.

like image 347
Caoilte Avatar asked Nov 14 '10 19:11

Caoilte


People also ask

Does sublist change the original List?

If you do any changes to the sublist, it will affect the original list as well.

What does List sublist do in Java?

Java List sublist() Method. The sublist() method of List Interface returns a view of the portion of this list between the inclusive and exclusive parameters. This method eliminates the need for explicit range operations.

What is sublist of a List?

Sublist is a portion of List. The subList() method of java. util. ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.

How do you truncate an ArrayList in Java?

Method. Truncate a list to a size by removing elements at its end, if necessary. if (limit > items. size()) { return new ArrayList<>(items); final List<T> truncated = new ArrayList<>(limit); for (final T item : items) { truncated.


2 Answers

Yes, subList is only a "view" onto the existing list. All the data is really in the original list. From the documentation:

The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

So yes, returning a sub-list will keep the original list from being garbage collected.

If you don't want that effect, you basically need to make a copy of the relevant sublist. For example:

return new ArrayList<Player>(listToSort.subList(0, 5));
like image 68
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet


subList creates a new instance of AbstractList.SubList, which keeps a reference to original list. So if you keep the variable returned by getHallOfFame, it will prevent the gc to clean listToSort.

like image 23
khachik Avatar answered Sep 19 '22 17:09

khachik