...
Code Block | ||
---|---|---|
| ||
public class InterceptExit { public static void main(String[] args) { InputStream in = new FileInputStream("file"); try { System.out.println("Regular code block"); // Abrupt exit such as ctrl + c key pressed System.out.println("This never executes"); } finally { in.close(); // this never executes either } } } |
Compliant Solution (addShutdownHook()
)
...
Code Block | ||
---|---|---|
| ||
public class Hook { public static void main(String[] args) { final InputStream in = new FileInputStream("file"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { hookShutdown(); } // Log shutdown and close all resources } in.close(); // ... } public static void hookShutdown() {}); // Log shutdown and close all resources... } } |
The JVM can abort for external reasons, such as an external SIGKILL
signal (UNIX) or the TerminateProcess
call (Microsoft Windows), or memory corruption caused by native methods. Shutdown hooks may fail to execute as expected in such cases, because the JVM cannot guarantee that they will be executed as intended.
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="1ce8b0120c5061de-066c9bf7-478044e1-8b6d8780-a17a641d3b62a9ea70d113fa"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | "Termination Strategy [REU]" | ]]></ac:plain-text-body></ac:structured-macro> |
CWE ID 705, "Incorrect Control Flow Scoping" |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5eb03bb3d743dc83-04292318-4ea740f1-bde1a137-c3ed03309d701c6714f502ad"><ac:plain-text-body><![CDATA[ | [[API 06 | AA. Bibliography#API 06]] | [Class Runtime | http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="bb0f0403abc3d669-7c4c5741-4c3e4f28-a1fdb7ed-53032183de144823ac463eac"><ac:plain-text-body><![CDATA[ | [[ISO/IEC TR 24772:2010 | AA. Bibliography#ISO/IEC TR 24772-2010]] | Section 6.46, "Termination Strategy [REU]" | ]]></ac:plain-text-body></ac:structured-macro> |
...