When is the finalize() method called in Java?
The finalize
method is called when an object is about to get garbage collected. That can be at any time after it has become eligible for garbage collection.
Note that it's entirely possible that an object never gets garbage collected (and thus finalize
is never called). This can happen when the object never becomes eligible for gc (because it's reachable through the entire lifetime of the JVM) or when no garbage collection actually runs between the time the object become eligible and the time the JVM stops running (this often occurs with simple test programs).
There are ways to tell the JVM to run finalize
on objects that it wasn't called on yet, but using them isn't a good idea either (the guarantees of that method aren't very strong either).
If you rely on finalize
for the correct operation of your application, then you're doing something wrong. finalize
should only be used for cleanup of (usually non-Java) resources. And that's exactly because the JVM doesn't guarantee that finalize
is ever called on any object.
protected void finalize() throws Throwable {}
- every class inherits the
finalize()
method from java.lang.Object- the method is called by the garbage collector when it determines no more references to the object exist
- the Object finalize method performs no actions but it may be overridden by any class
- normally it should be overridden to clean-up non-Java resources ie closing a file
if overridding
finalize()
it is good programming practice to use a try-catch-finally statement and to always callsuper.finalize()
. This is a safety measure to ensure you do not inadvertently miss closing a resource used by the objects calling classprotected 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 ignoredfinalize()
is never run more than once on any object
quoted from: http://www.janeg.ca/scjp/gc/finalize.html
You could also check this article:
- Object finalization and cleanup
In general it's best not to rely on finalize()
to do any cleaning up etc.
According to the Javadoc (which it would be worth reading), it is:
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
As Joachim pointed out, this may never happen in the life of a program if the object is always accessible.
Also, the garbage collector is not guaranteed to run at any specific time. In general, what I'm trying to say is finalize()
is probably not the best method to use in general unless there's something specific you need it for.