未调用java finalize()
为什么这里没有调用finalize()
。代码编译并运行成功,但没有任何输出
package temp;
public class Temp {
int i;
Temp(int j) {
i = j;
}
public void finalize() {
if (i == 10) {
System.out.println("Finalize called.");
}
}
public static void main(String[] args) {
Temp obj = new Temp(10);
System.gc();
}
}
# 1 楼答案
碰巧我在读Effective Java
第7项:避免使用终结器
另一个来自pdf
基于此使用系统。gc只会增加终结器被执行的几率,重要的是,使用它并不能保证它将运行垃圾收集,它只是向jvm建议
另一个
# 2 楼答案
添加
obj = null;
使引用为null,然后将调用finalize方法。Thsi再次不是一种保证行为,对我来说,有1-2次我能在5次中说出它输出
# 3 楼答案
创建对象时,会调用构造函数,但不会调用finalize()方法,因此需要引用实例obj中的函数,此处为系统。gc();没有任何区别或调用了方法finalize()
# 4 楼答案
您对
System.gc();
的调用没有任何区别,因为您的Temp
实例有一个引用(obj
),所以它不符合垃圾收集的条件即使它符合垃圾收集的条件,调用
System.gc();
也不一定会立即收集所有没有引用的对象