我有这个代码我想知道当时有多少对象可以清楚地调用system.gc();在java? 这是我的代码:
public class GCTest {
static class A {
private String myName;
public A(String myName) {
this.myName = myName;
}
}
public static void main(String[] args) {
A a1 = new A("a1");
A a2 = new A("a2");
ArrayList list = new ArrayList();
list.add(a1);
A[] mas = new A[2];
mas[0] = a2;
a2 = a1;
clear(mas);
a1 = null;
a2 = null;
System.gc();
// other code going
}
private static void clear(A[] mas) {
mas = null;
}
}
答案 0 :(得分:1)
否对象将可用于GC。
<强>为什么?强>
list.add(a1);
- &gt;确保您拥有强参考至a1
。
mas[0] = a2;
- &gt;确保您拥有强参考至a2
。
private static void clear(A[] mas) { // doesn't affect the actual mas array
mas = null;
}
答案 1 :(得分:1)
这通常无关紧要,答案是一个实施细节,其中许多因素起作用,包括字符串实习,构建&#34;隐藏&#34;对象,可能的自动GC和积极的对象集合,就语言而言仍然在范围内。
在任何情况下,您对此代码段的答案最接近的事情都来自这个推理:
new
表达式)。System.gc()
时,将您的本地变量引用的所有对象交叉。