我读到该对象在以下情况下有资格进行垃圾回收。
- 该对象的所有引用均显式设置为 null。
- 对象是在 block 内创建的,并且引用超出了范围 一旦控制退出该 block 。
- 如果一个对象持有另一个对象的引用,则父对象设置为 null 对象,并且当您将容器对象的引用设置为 null、子对象或 包含的对象自动成为垃圾对象 Collection 。
但是有什么办法可以识别出符合垃圾收集条件的对象是由垃圾收集器收集的吗?
最佳答案
您可以实现Object#finalize()
方法
public class Driver {
public static void main(String[] args) throws Exception {
garbage();
System.gc();
Thread.sleep(1000);
}
public static void garbage() {
Driver collectMe = new Driver();
}
@Override
protected void finalize() {
System.out.println(Thread.currentThread().getName() + ": See ya, nerds!");
}
}
打印内容
Finalizer: See ya, nerds!
因此您可以在收集之前进行拦截。 javadoc 指出
The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads;
而且
The finalize method is never invoked more than once by a Java virtual machine for any given object.
关于java - java中是否可以识别对象是否被垃圾收集器收集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20528307/