/**
* 该类用于演示在对象的finalize()方法中复活对象(来自《实战java虚拟机》-葛一鸣)
* 2017年4月4日 下午9:06:00
* @version v1.0
*/
public class CanReliveObj
{
public static CanReliveObj obj;
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("CanReliveObj finalize called !!!");
obj = this;
}
@Override
public String toString() {
return "I am canReliveObj";
}
public static void main(String[] args) throws InterruptedException {
obj = new CanReliveObj();
obj = null;
System.gc();
Thread.sleep(1000);
if(obj == null) {
System.out.println("obj is null");
} else {
System.out.println("obj is alive");
}
System.out.println("第2次调用gc后");
obj = null;
System.gc();
Thread.sleep(1000);
if(obj == null) {
System.out.println("obj is null");
} else {
System.out.println("obj is alive");
}
}
}
运行上述代码后结果如下
CanReliveObj finalize called !!!
obj is alive
第2次调用gc后
obj is null