...
The addShutdownHook
method of java.lang.Runtime
helps to perform clean-up operations in the unusual termination scenario. When the shutdown is initiated, the hook thread starts to run concurrently with other JVM threads.
Wiki Markup |
---|
According to \[[API 06|AA. Java References#API 06]\] Class {{Runtime}}, method {{addShutdownHook}}: |
A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine. Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook.
Since the JVM is in a sensitive state during this stage, some precautions must be taken:
...
Code Block | ||
---|---|---|
| ||
public class Hook { public static void main(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { hookShutdown(); } }); //other code } public static void hookShutdown() { // Log shutdown and close all resources } } |
It is still possibly for the JVM to abort due to external issues, such as an external SIGKILL
signal (UNIX) or the TerminateProcess
call (Microsoft Windows), or memory corruption caused by native methods. In such cases, it is not guaranteed that the hooks will execute as expected.
Risk Assessment
Allowing inadvertent calls to System.exit()
may lead to denial-of-service attacks.
...
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\] [method checkExit()|http://java.sun.com/j2se/1.4.2/docs/api/java/lang/SecurityManager.html#checkExit(int)], Class Runtime, method addShutdownHook \[[Kalinovsky 04|AA. Java References#Kalinovsky 04]\] Chapter 16 Intercepting a Call to System.exit \[[Austin 00|AA. Java References#Austin 00]\] [Writing a Security Manager|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed2.html] \[[Darwin 04|AA. Java References#Darwin 04]\] 9.5 The Finalize Method |
...
EXC03-J. Try to recover gracefully from system errors 10. Exceptional Behavior (EXC) EXC30-J. Do not exit abruptly from a finally block