Friday, 25 July 2008

What does finalize() do in Java?

Every class inherits finalize from java.lang.Object. The method is called by the garbage collector when it determines no more references to the object exist. Should normally be overriden to clean up non-Java resources e.g. closing a file. Good idea to free resources in a try-catch-finally and then call super.finalize(). Finalization is never run more than once on any object. It's generally best to clean resources in a try-catch-finally rather than in finalize() to ensure timely cleanup.

Important note: when an application exits, the JVM will NOT execute finalizers of any object left on the heap. To change this behaviour you need to call the method runFinalizersOnExit, this method is deprecated however as it can result in deadlock.

Objects can be resurrected using finalizers in Java. finalize() is called as an object has no more references. But suppose finalize then adds the object to a static "live" linked list. The object now has an additional reference and can't be garbage collected.

No comments: