Java Reference
In-Depth Information
Discussion
One way of performing application-level cleanup is the runtime method
addShut-
downHook()
, to which you pass a nonstarted
Thread
subclass object.
If the virtual machine
has a chance
, it runs your shutdown hook code as part of JVM termination. This normally
works, but won't happen if 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 struc-
tures.
you not to use those earlier in this chapter) and a shutdown hook. The program normally
exits while holding a reference to the object with the
finalize()
method. If run with
-f
as
an argument, it “frees” the object and “forces” a GC run by calling
System.gc()
; only in
this case does the
finalize()
method run. The shutdown hook is run in every case.
Example 8-1. ShutdownDemo
public
public class
class
ShutdownDemo
ShutdownDemo
{
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
Exception
{
// Create an Object with a finalize() method - Bad idea!
Object f
=
new
new
Object
() {
public
public
void
throws
Throwable
{
System
.
out
.
println
(
"Running finalize()"
);
super
void
finalize
()
throws
super
.
finalize
();
}
};
// Add a shutdownHook to the JVM
Runtime
.
getRuntime
().
addShutdownHook
(
new
new
Thread
() {
public
public
void
void
run
() {
System
.
out
.
println
(
"Running Shutdown Hook"
);
}
});
// Unless the user puts -f (this-program-specific argument for "free") on
// the command line, call System.exit while holding a reference to
// Object f, which can therefore not be finalized().
iif
(
args
.
length
==
1
&&
args
[
0
].
equals
(
"-f"
)) {
f
=
null
null
;
System
.
gc
();
}