...
Java provides two options for program termination: Runtime.exit()
(this is equivalent to System.exit()
or returning from main() ) and Runtime.halt()
.
Runtime.exit()
Runtime.exit() is the typical way of exiting a program:
Terminates the currently running Java virtual machine by initiating its shutdown sequence. This method never returns normally. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is done the virtual machine halts.If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely. If shutdown hooks have already been run and on-exit finalization has been enabled then this method halts the virtual machine with the given status code if the status is nonzero; otherwise, it blocks indefinitely.
The System.exit method is the conventional and convenient means of invoking this method.
...
invoking this method.
The Runtime.addShutdownHook()
method can be used to customize Runtime.exit()
to perform additional actions at program termination.
This method takes a single Thread
, which must be initalized but unstarted. Then, when the JVM begins to shut down, the thread will be run. Since the JVM usually has a fixed time to shut down, these threads should not be long-running and should not attempt user interaction.
...