Search code examples
javaexitshutdownshutdown-hook

Differentiate shutdowns more than Runtime.setShutdownHook() in Java


Is there a way to add a shutdown hook that is only fired when the program is shut down because of a System shutdown.

I don't want the code to run when the code finishes regularly, only on other Exits.
With addShutDownHook the Thread runs no matter how the program terminated


Solution

  • You can setup a security policy for your program or add a SecurityManager.

    Then when the System.exit is invoked (a regular exit), the SecurityManager's checkExit method will be invoked. Inside that method, you can de-register the shutdown hook using Runtime#removeShutdownHook.