在 Java 中,有一个嵌套的静态类Human
,我想知道在清理map
变量后是否可以使其可用于垃圾收集。就在doSomeCode()
我打电话System.gc()
并添加Thread.sleep(60000)
以等待垃圾收集器拾取未引用的map
内容之前的那一刻,但没有办法 - 它似乎map
存在于程序中,除非它即将完成。我的问题是我需要释放内存,否则会得到OutOfMemoryError
.
你认为是什么阻止map
了阶级的财产Human
被回收?是因为Human
类是静态的,因此它的所有成员都不能被垃圾收集吗?
import java.util.List;
import java.util.ArrayList;
import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.IntObjectOpenHashMap;
public class TestNestedStaticClass {
public static class Human {
String name = null;
List<Human> children = null;
// some data about family members
IntObjectMap<int[]> map = null;
public Human(String name) { this.name = name; }
}
public static void main(String[] args) {
final List<Human> family = new ArrayList<Human>();
for (int i = 0; i < 1000; i++) {
// create and get the family member
family.add(new Human("givenName"));
Human h = family.get(i);
// create map and add some data
h.map = new IntObjectOpenHashMap<int[]>();
for (int j = 0; j < 100; j++) {
int[] array = new int[1500];
h.map.put(j, array);
}
}
// ...
// at some point we want to free the memory occupied by
// family.get(i).map for all i from 0 to 1000, so we do:
for (int i = 0; i < 1000; i++) {
// get the family member
Human h = family.get(i);
// explicitly remove references from the map
for (int j = 0; j < 100; j++) {
h.map.remove(j);
}
// cleanup
h.map.clear();
h.map = null;
}
// ...
doSomeCode();
}
}