lazyguy
lazyguy

Reputation: 107

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

Upvotes: 4

Views: 182

Answers (2)

M A
M A

Reputation: 72854

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.

Upvotes: 3

Gili
Gili

Reputation: 90043

I don't think that is possible as of JDK 1.8. At least, I haven't heard of such a mechanism.

Of course, you could add such support yourself using JNI (if the underlying operating system supports it).

Upvotes: 1

Related Questions