2

I have Windows Desktop application based on Java.

I have kept defaultuncaughtexceptionahandler and shutdown hook in my application.

I have some user called exit points like , user clicks on exit, some error conditions etc. All the user exit points have proper logs which will be followed by the log in shutdown hook.

Now for one of my user the application is getting exited from time to time . here user is not calling any user exit points. Shutdown hook logs are printed. There is no exception from defaultuncaughtexception handler.

I am not able to find who calls the system.exit and hence the shutdown hook . Can i somehow find what calls the shutdown hook or system.exit () ? Printing of shutdown hooks makes me think that is a proper jvm shutdown not an abrupt one.

Best Regards, Saurav

saurav
  • 5,388
  • 10
  • 56
  • 101

2 Answers2

7

If you suspect that someone invokes System.exit(…) or a similar function explicitly, you can intercept it with a SecurityManager:

System.setSecurityManager(new SecurityManager() {
    @Override
    public void checkExit(int status) {
        new Exception("exit attempt with return code "+status).printStackTrace();
    }
    // note that all dedicated check... methods delegate to the two below,
    // so overriding these is sufficient to enable all other actions
    @Override
    public void checkPermission(Permission perm, Object context) { }

    @Override
    public void checkPermission(Permission perm) { }
});

This, however, will not intercept shutdown caused by external events, like a TERM signal, etc.

Holger
  • 285,553
  • 42
  • 434
  • 765
1

If you are running OpenJDK / Oracle JDK, you may register a "system" shutdown hook which will dump a thread that has initiated shutdown process:

    sun.misc.SharedSecrets.getJavaLangAccess().registerShutdownHook(7, true,
            () -> {
                System.out.println(Thread.currentThread());
                new Exception("Who called me?").printStackTrace();
            });

This will work even for external events like Ctrl+C.

apangin
  • 92,924
  • 10
  • 193
  • 247
  • I tried ur sample code in my main method of spring boot application. I ma getting 2 error 1."Shutdown hook at slot i already registered" 2.Index out of bound exception if uses i value greater than 10 – StackOverFlow Aug 28 '20 at 13:34