finalize method

suggest change

This is a protected and non-static method of the Object class. This method is used to perform some final operations or clean up operations on an object before it gets removed from the memory.

According to the doc, this method gets called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

finalize() is not called while the object is still reachable. After it becomes unreachable, nothing guarantees that a collector will run it. That’s why it’s better not to rely on this method. The FileInputStream fragment below matches older JDKs. Java 9 and later close the descriptor with a Cleaner instead of this finalizer.

In Java core libraries some usage examples could be found, for instance in FileInputStream.java:

protected void finalize() throws IOException {
    if ((fd != null) &&  (fd != FileDescriptor.in)) {
        /* if fd is shared, the references in FileDescriptor
         * will ensure that finalizer is only called when
         * safe to do so. All references using the fd have
         * become unreachable. We can call close()
         */
        close();
    }
}

In this case it’s the last chance to close the resource if that resource has not been closed before.

Generally it’s considered bad practice to use finalize() method in applications of any kind and should be avoided.

Finalizers are not meant for freeing resources (e.g., closing files). The garbage collector gets called when (if!) the system runs low on heap space. You can’t rely on it to be called when the system is running low on file handles or, for any other reason.

The intended use-case for finalizers is for an object that is about to be reclaimed to notify some other object about its impending doom. A better mechanism now exists for that purpose—the java.lang.ref.WeakReference<T> class. If you think you need to write a finalize() method, a WeakReference alone does not run cleanup. Pair a reference with a ReferenceQueue, or use java.lang.ref.Cleaner (Java 9). If that will not solve the problem, the design needs a different owner for the resource.

For further reading here is an Item about finalize() method from “Effective Java” book by Joshua Bloch.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents