4

If I've got a Java program that can exit for various reasons, like:

  • because the main window, which is set to "exit on close", was closed

  • because there are some System.exit( 0 ) in the code

  • because there are no more window at all (and none was set to exit on close) but there's still several threads running then at one point there are only daemon threads running and hence the program exits.

And I've got a shutdown hook installed (which is running fine).

Is there any way to know, from my shutdown hook, what caused the Java program to exit?

(note that I'm not asking if it's a good idea or not to have System.exit(...) spread over the codebase: this is not what this question is about)

Basically I'd like to know if I'm forced myself to intercept every single possible JVM exit point and add infos there or if there's already a method allowing to do that.

Cedric Martin
  • 5,945
  • 4
  • 34
  • 66

2 Answers2

4

You can add a SecurityManager which will be called on System exit (to determine if its allowed). You can save where this was called for later or deal with it in the SecurityManager.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • what do you mean by *"You can save where this was called for later..."* Would a *SecurityManager* allow me to get the exact class/line at which, for example, a *System.exit* call was made? – Cedric Martin Nov 22 '11 at 16:49
  • 2
    You can get a stack trace with Thread.currentThread().getStackTrace(). The SecurityManager gets called when security sensitive operations are performed (otherwise its just a class/object) – Peter Lawrey Nov 22 '11 at 18:26
  • Inside your security manager, you can construct a `Throwable`, then retrieve the stack trace from it using either `printStackTrace()` or `getStackTrace()`. – John Haager Nov 22 '11 at 18:27
-1

Your shutdown hook will just run your runnable logic in a separate thread when the JVM is shutting down. You cant do anything more with this.

Drona
  • 6,886
  • 1
  • 29
  • 35