基本上,我尝试进行测试并遇到有关垃圾收集器的问题:
以下代码片段中有多少个可用于 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;
}
}
我认为有 2 个对象可用:
1)arr – 清除(arr)后
2)n2 – n2=null 之后
我不确定 arr – 是一个对象,可能 arr 是一系列对象。另外,我不确定 StaticNestedClass 的实例,它是静态的并且位于 PermGen 中,而不是作为典型对象位于堆中。 GC 在永久代和堆中都有效吗?
最佳答案
我认为:`没有对象已准备好进行 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;
}
所以,基本上没有对象准备好进行 GC。
关于java - System.gc() 的可用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24836648/