View RSS Feed

My Java Tips

Finalize

Rate this Entry
by , 05-24-2011 at 01:46 PM (1748 Views)
All Java classes inherits the finalize() method from java.lang.Object and this method is called by the garbage collector when it determines no more references to the object exist.

The finalize method performs no actions but it may be overridden by any class. It is overridden to clean-up non-Java resources ie closing a file, closing a connection etc. In overridding finalize() it is a good programming practice to use a try-catch-finally statement and to always call super.finalize().

Java Code:
protected void finalize() throws Throwable {
    try {
        close();        // close open files
    } finally {
        super.finalize();
    }
}
Any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored.
Remember that finalize() is never run more than once on any object .

Submit "Finalize" to Facebook Submit "Finalize" to Digg Submit "Finalize" to del.icio.us Submit "Finalize" to StumbleUpon Submit "Finalize" to Google

Tags: finalize Add / Edit Tags
Categories
Java SE

Comments