有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

未调用java finalize()

为什么这里没有调用finalize()。代码编译并运行成功,但没有任何输出

package temp;

public class Temp {

    int i;

    Temp(int j) {
        i = j;
    }

    public void finalize() {
        if (i == 10) {
            System.out.println("Finalize called.");
        }
    }

    public static void main(String[] args) {
        Temp obj = new Temp(10);
        System.gc();
    }

}

共 (4) 个答案

  1. # 1 楼答案

    碰巧我在读Effective Java

    第7项:避免使用终结器

    Finalizers are unpredictable, often dangerous, and generally unnecessary. -Effective Java (page 50)

    另一个来自pdf

    Don’t be seduced by the methods System.gc and System.runFinalization . They may increase the odds of finalizers ge tting executed, but they don’t guaran- tee it. The only methods that claim to guarantee finalization are System.runFi- nalizersOnExit and its evil twin, Runtime.runFinalizersOnExit . These methods are fatally flawed and have been deprecated [ThreadStop].

    基于此使用系统。gc只会增加终结器被执行的几率,重要的是,使用它并不能保证它将运行垃圾收集,它只是向jvm建议

    另一个

    Not only does the language specification provide no guarantee that finalizers will get executed promptly; it provides no guarantee that they’ll get executed at CHAPTER 2 CREATING AND DESTROYING OBJECTS 28 all. It is entirely possible, even likely, that a program terminates without executing finalizers on some objects that are no longer reachable

  2. # 2 楼答案

    添加obj = null;使引用为null,然后将调用finalize方法。Thsi再次不是一种保证行为,对我来说,有1-2次我能在5次中说出它

     public static void main(String[] args) {
            Temp obj = new Temp(10);
            obj  = null;
            System.gc();
        }
    

    输出

    hi10
    Finalize called.
    
  3. # 3 楼答案

    创建对象时,会调用构造函数,但不会调用finalize()方法,因此需要引用实例obj中的函数,此处为系统。gc();没有任何区别或调用了方法finalize()

  4. # 4 楼答案

    您对System.gc();的调用没有任何区别,因为您的Temp实例有一个引用(obj),所以它不符合垃圾收集的条件

    即使它符合垃圾收集的条件,调用System.gc();也不一定会立即收集所有没有引用的对象