Search code examples
javashutdownshutdown-hook

How to get return code in shutdown hook


I need to modify JVM return code according to my application result.

But it is risky to explicitly call System.exit(code) coz the application is complicated and it is hard to identify the end of running threads.

So I come up with using shutdown hook to modify the return code before JVM exit.

But there is a problem that how can I get the original return code of JVM coz it may be an error code not 0.


Solution

  • You should not call exit method in shutdown hook, System.exit(status) internally calls Runtime.getRuntime().exit(status); which will cause your application to block indefinitely.

    As per the JavaDoc

    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.

    You don't have access to status, as it could change even after all shutdown hooks are called.