Java and manually executing finalize

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.

Leave a Comment