java - java中是否可以识别对象是否被垃圾收集器收集?

标签 java garbage-collection

我读到该对象在以下情况下有资格进行垃圾回收。

  1. 该对象的所有引用均显式设置为 null。
  2. 对象是在 block 内创建的,并且引用超出了范围 一旦控制退出该 block 。
  3. 如果一个对象持有另一个对象的引用,则父对象设置为 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/

相关文章:

Java堆栈溢出与递归

Java Awt 钢笔工具 : Graphic disappeared

Java垃圾收集器

java - 了解和比较 GarbageCollectorMXBean 和 jstat 实用程序

java - AutoCloseable 与垃圾回收的关系

java - 编译使用 geany\u0000 编写的程序时出现非法字符错误

java - 将错误从服务层传回 View

java - 如何以编程方式禁用屏幕锁定密码。

java - 我应该在我的 java 持久性项目中调用 System.gc() 吗?

garbage-collection - 垃圾收集 - 根节点