public final class Main { static { System.out.println("Hello World"); System.exit(0); } }
The static block is first executed as soon as the class is loaded before the main(); method is called main(); , and therefore, before calling main() System.exit(0) initiates the shutdown of the VM.
The System.exit method stops the execution of the current thread, and all others are dead in their tracks. When System.exit is called, the virtual machine performs two cleanup tasks before closing.
First, it executes all final locks registered in Runtime.addShutdownHook . This is useful for allocating resources external to the virtual machine. Use disconnect hooks for behavior that must occur before the VM exits.
The second cleaning task performed by the virtual machine when invoking System.exit concerns finalizers. If either System.runFinalizersOnExit or its evil twin Runtime.runFinalizersOnExit , VM runs finalizers on all objects that have not yet been finalized. These methods were obsolete a while ago and not without reason. Never call System.runFinalizersOnExit or Runtime.runFinalizersOnExit for any reason: they are some of the most dangerous methods in Java libraries. Calling these methods can cause finalizers to run on live objects, while other threads simultaneously manipulate them, resulting in unstable behavior or deadlocks.
Thus, System.exit immediately stops all program flows; This does not finally force the blocks to execute, but it starts the final hooks before the VM stops. Use interrupts to complete external resources when the virtual machine shuts down. You can pause a virtual machine without intercepting it when closing System.halt , but this method is rarely used.
Lion Dec 24 '11 at 2:06 p.m. 2011-12-24 14:06
source share