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 in erratic behavior or deadlock.
So what if you need some kind of cleanup? You must take
responsibility for defining a method and invoking it before you let
any object of that class go out of reference. You might call such a
method cleanUp( )
.
Java 2 SDK 1.3 introduced the runtime method
addShutdownHook( )
, to which you pass a non-started
Thread
subclass object; if the virtual machine has
a chance, it runs your shutdown hook code as part of termination.
This will normally work, unless the VM was terminated abruptly as by
a kill signal on Unix or a KillProcess on Win32, or the VM aborts due
to detecting internal corruption of its data structures.
The bottom line? There’s no guarantee, but finalizers and shutdown hooks both have pretty good odds of being run.
3.145.103.154