我试图查看垃圾收集器何时“垃圾收集”一个对象。根据文档,当垃圾收集器“删除”一个对象时,finalize() 方法被调用一次。
我试图重写 finalise() 以查看我是否可以看到在我使对象无效之后调用它的时间点,但我似乎在无限期地等待。这应该有效吗?
class Dog{
ZiggyTest2 z;
public Dog(ZiggyTest2 z){
this.z = z;
}
protected void finalize() throws Throwable {
try {
synchronized(z){
System.out.println("Garbage collected");
z.notify();
}
} finally {
super.finalize();
}
}
}
还有主类:
class ZiggyTest2{
public static void main(String[] args){
ZiggyTest2 z = new ZiggyTest2();
Dog dog = new Dog(z);
synchronized(z){
try{
dog = null;
z.wait();
}catch(InterruptedException ie){
System.out.println("Interrupted");
}
}
}
}
我想做的是在我使 Dog 对象无效后看到 finalise() 方法被调用。这就是为什么我将 notify() 语句放在 finalize() 方法中的原因。它不起作用,因为它一直在等待..
编辑
谢谢大家。在我修改 ZiggyTest2 以添加 System.gc(); 之后我让它工作了;
class ZiggyTest2{
public static void main(String[] args){
ZiggyTest2 z = new ZiggyTest2();
Dog dog = new Dog(z);
synchronized(z){
try{
dog = null;
System.gc();
z.wait();
}catch(InterruptedException ie){
System.out.println("Interrupted");
}
}
}
}
输出:
C:\>java ZiggyTest2
Garbage collected
最佳答案
尝试在设置 dog = null 后添加 System.gc()
。
关于java - 观察垃圾收集器 bin 一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8645055/