The Finalize Method

Problem

You want to have some action taken when your objects are removed from service.

Solution

Use finalize( ) but don’t trust it; or, write your own end-of-life method.

Discussion

Developers coming from a C++ background tend to form a mental map that has a line of equivalency drawn from C++ destructors to Java finalizers. In C++, destructors are called automatically when you delete an object. Java, though, has no such operator as delete; objects are freed automatically by a part of the Java runtime called the garbage collector, or GC. GC runs as a background thread in Java processes and looks around every so often to see if there are any objects that are no longer referred to by any reference variable. When it runs, as it frees objects, it calls their finalize( ) methods.

For example, what if you (or some code you called) invoke System.exit( ) ? In this case the entire JVM will cease to exists (assuming there isn’t an applet-style security manager to deny it permission to do so) and the finalizer is never run. Similarly, a “memory leak” or mistakenly held reference to your object will also prevent finalizers from running.

Can’t you just ensure that all finalizers get run simply by calling System.runFinalizersOnExit(true) ? Not really! This method is deprecated (see Section 1.10); the documentation notes:

This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.