我很想知道最新的JVM如何处理由以下方法保留的垃圾收集内存。
public List<Player> getHallOfFame() { ArrayList<Player> listToSort = new ArrayList<Player>(map.values()); Collections.sort(listToSort, comparator); return listToSort.subList(0, 5); }在最坏的情况下,我可以想象只要还有listToSort列表的引用,JVM就会将listToSort的全部内容listToSort在内存中。 有谁知道这是否确实如此? 我特别感兴趣的链接可以证明这种方式或其他特定的JVM。
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.
最满意答案
是的, subList只是对现有列表的“查看”。 所有数据都在原始列表中。 从文档:
返回的列表由此列表支持,因此返回列表中的非结构化更改将反映在此列表中,反之亦然。
所以是的,返回一个子列表将保持垃圾收集的原始列表。
如果你不想要这种效果,你基本上需要制作相关子列表的副本。 例如:
return new ArrayList<Player>(listToSort.subList(0, 5));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));更多推荐
发布评论