Finalize Methods are a Bad Idea

What is finalize?

Every class in Java inherits a finalize method from java.lang.Object.   The garbage collector invokes this method after it determines that an object is eligible for garbage collection but before it actually reclaims the memory.    

If you look at the JDK source code, the finalize method doesn't actually do anything:

protected void finalize() throws Throwable { }

However, your class may override this to provide an implementation.   The idea is that it provides an opportunity to close external resources such as open streams, files, and network connections.

protected void finalize() throws Throwable {

Issues with finalize

The finalize method is never guaranteed to be called because an object may never become eligible for garbage collection.  This can occur for a couple reasons:

  • The object is reachable throughout the lifetime of the program
  • No garbage collection cycles run between the time object becomes eligible and the end of the program  

In summary, you should not rely on finalize to perform cleanup of your resources or to provide any important functionality.