Java and manually executing finalize

前端 未结 3 2092
你的背包
你的背包 2020-12-01 16:32

If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this objec

3条回答
  •  甜味超标
    2020-12-01 17:08

    According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it:

    private static class Blah
    {
      public void finalize() { System.out.println("finalizing!"); }
    }
    
    private static void f() throws Throwable
    {
       Blah blah = new Blah();
       blah.finalize();
    }
    
    public static void main(String[] args) throws Throwable
    {
        System.out.println("start");
        f();
        System.gc();
        System.out.println("done");
    }
    

    The output is:

    start
    finalizing!
    finalizing!
    done

    Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually.

提交回复
热议问题