java - 未引用的对象可以再次引用吗?

标签 java garbage-collection

正如主题所说:未引用的对象可以再次引用吗?

我在http://www.javatpoint.com/corejava-interview-questions-4遇到了这个问题Q120。我尝试用谷歌搜索这个但没有找到任何链接。我们实际上如何做到这一点?

最佳答案

下面的示例不是“野外”示例,但它演示了如何通过 finalize 方法“复活”未引用的对象。这种情况只可能发生一次。如果第一个实例的对象第二次变为未引用,则不会再次调用 finalize() 方法。

public class Resurrect {

    static Resurrect resurrect = null;

    public static void main(String[] args) {
        Resurrect localInstance = new Resurrect();
        System.out.println("first instance: " + localInstance.hashCode());

        // after this code there is no more reference to the first instance
        localInstance = new Resurrect();
        System.out.println("second instance: " + localInstance.hashCode());

        // will (in this simple example) request the execution of the finalize() method of the first instance
        System.gc(); 
    }

    @Override
    public void finalize() {
        resurrect = this;
        System.out.println("resurrected: " + resurrect.hashCode());
    }
}

关于java - 未引用的对象可以再次引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743096/

相关文章:

java - 使用 Joda 时间库从 UTC 到 IST 的转换在 JAVA 中返回相同的值

java - JUnit5:如何通过单个断言调用断言一个对象的多个属性?

java - 均衡java中的两个复杂对象(两个对象由其他对象制成)

java - 如何访问泛型类型的类的类成员?

java - Angular 从 Spring RestController 获取图像并缓存它

c - 当C库使用不透明结构指针时,如何解决cgo中的 "bad pointer in write barrier"panic

java - 为 CPU 缓存友好性调整 Java 类

Queue dequeue()示例代码中的Java垃圾回收

java : How garbage collection works for static final String object declared in interface and class

c++ - 将元类级别添加到 C++ 对象模型