tags:

views:

1738

answers:

2

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 object?

This would be an approximate example:

MyObject m = new MyObject();

m.finalize();

m = null;

System.gc()

Would the explicit call to finalize make the JVM's garbage collector not to run the finalize method on object m??

A: 

The finalize method is never invoked more than once by a JVM for any given object. You shouldn't be relying on finalize anyway because there's no guarantee that it will be invoked. If you're calling finalize because you need to execute clean up code then better to put it into a separate method and make it explicit, e.g:

public void cleanUp() {
  .
  .
  .
}

myInstance.cleanUp();
John Topley
+10  A: 

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.

Outlaw Programmer