4

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

lazyguy
  • 107
  • 6

2 Answers2

3

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.

M A
  • 71,713
  • 13
  • 134
  • 174
  • You can't unregister a shutdown hook after the shutdown started, but with your method you can coordinate everything over a field – lazyguy Oct 24 '14 at 21:12
  • 1
    @lazyguy Inside the shutdown hook there is no portable way to know the reason why the JVM is shutting down. – M A Oct 24 '14 at 21:15
  • Is there an easy way to create a security Manager which by default allows everything, or do you have to Override all the methods with empty ones? – lazyguy Oct 24 '14 at 21:30
  • 1
    @lazyguy That's a different topic :) You can look that up or ask a new question. – M A Oct 24 '14 at 21:32
  • @lazyguy after some more thought: I just added a field in which each thread registers when shutting down properly. Then the shutdownHook just checks whether all threads shut down properly. This is much easier than using a SecurityManager – lazyguy Oct 24 '14 at 21:58
1

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).

Gili
  • 86,244
  • 97
  • 390
  • 689