Java Reference
In-Depth Information
technique, printing both Hello world and Goodbye world , as expected:
public class HelloGoodbye {
public static void main(String[] args) {
System.out.println("Hello world");
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
System.out.println("Goodbye world");
}
});
System.exit(0);
}
}
The second cleanup task performed by the VM when System.exit is called concerns finalizers. If
either System.runFinalizersOnExit or its evil twin Runtime.runFinalizersOnExit has been
called, the VM runs the finalizers on all objects that have not yet been finalized. These methods
were deprecated a long time ago and with good reason. Never call System.runFinalizersOnExit
or Runtime.runFinalizersOnExit for any reason: They are among the most dangerous
methods in the Java libraries [ThreadStop] . Calling these methods can result in finalizers being
run on live objects while other threads are concurrently manipulating them, resulting in erratic
behavior or deadlock.
In summary, System.exit stops all program threads immediately; it does not cause finally blocks
to execute, but it does run shutdown hooks before halting the VM. Use shutdown hooks to
terminate external resources when the VM shuts down. It is possible to halt the VM without
executing shutdown hooks by calling System.halt , but this method is rarely used.
< Day Day Up >
 
 
Search WWH ::




Custom Search