判断一个对象是否已被垃圾回收器回收了
重写父类的finalize()方法,如果这个方法被调用了,那么就说明它已经被回收了,如下:
public class ReferDemo {
public static void main(String[] args) {
Test t = new Test();
}
}
class Test{
@Override
protected void finalize() throws Throwable {
System.out.println("回收了");
super.finalize();
}
}
但是,你运行这个代码的时候,会发现,并不会打印出“回收了”,即便是调用System.gc(); 也不会回收,这是因为t为强引用,那,怎么让GC回收它呢
方法一:
将要回收的对象=null
public class ReferDemo {
public static void main(String[] args) {
Test t = new Test();
System.gc();
System.out.println("over.....");
}
}
class Test{
@Override
protected void finalize() throws Throwable {
System.out.println("回收了");
super.finalize();
}
}
方法二:
把强引用转换为弱引用
public class ReferDemo {
public static void main(String[] args) {
WeakReference<Test> wr = new WeakReference<Test>(new Test());//弱引用
System.gc();
Test t = wr.get();
System.out.println("over....."+t);
}
}
class Test{
@Override
protected void finalize() throws Throwable {
System.out.println("回收了");
super.finalize();
}
}
本文探讨了如何通过改变对象的引用类型实现Java对象的回收,包括直接赋值为null和使用弱引用的方法,以及在Java中重写finalize()方法在对象被垃圾回收时触发的情况。
5万+

被折叠的 条评论
为什么被折叠?



