基本上,我尝试进行测试并坚持关于垃圾收集器的问题:
以下代码段中有多少可用于System.gc()的对象:
public class WorkGC {
static class StaticNestedClass {
private String name;
public StaticNestedClass(String name) {
this.name = name;
}
}
public static void main(String[] args) {
StaticNestedClass n1 = new StaticNestedClass("n1");
StaticNestedClass n2 = new StaticNestedClass("n2");
Collection list = new ArrayList();
list.add(n1);
StaticNestedClass[] arr = new StaticNestedClass[2];
arr[0] = n2;
n2 = n1;
clear(arr);
n1 = null;
n2 = null;
System.gc();
//the rest of the code
}
private static void clear(StaticNestedClass[] arr) {
arr = null;
}
}
我认为有两个对象可用:
1)arr - 在清除(arr)之后
2)n2 - 在n2 = null之后
我不确定arr - 是一个对象,可能是arr是一系列对象。另外,我不确定StaticNestedClass的实例,它是静态的并且位于PermGen中 - 而不是作为典型对象在Heap中。 GC是否在PermGen以及堆中工作?
答案 0 :(得分:1)
我认为:`没有对象为GC做好准备。 我认为这将是情景:
public static void main(String[] args) {
StaticNestedClass n1 = new StaticNestedClass("n1"); // 1st object created
StaticNestedClass n2 = new StaticNestedClass("n2"); // 2nd object created
Collection list = new ArrayList(); // 3rd object
list.add(n1); // n1 has a strong reference, so n1 is not ready for GC.
StaticNestedClass[] arr = new StaticNestedClass[2];// 4th object created
arr[0] = n2; //n2 has strong reference, so, even n2 is not ready.
n2 = n1; // both n1 and n2 point to same object as that of n1. but arr[0] still references n2.
clear(arr); // you are passing references by value. SO, this has absolutely no effect on GC.
n1 = null;// Object pointed to by n1 is still being referenced by n2
n2 = null; //Object pointed to by n1 has a reference in the list.
System.gc();
//the rest of the code
}
private static void clear(StaticNestedClass[] arr) {
arr = null;
}
因此,基本上No Object已准备好用于GC。