Finding out who calls jvm shutdown hook

前提是你 提交于 2019-12-19 05:08:11

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/42091522/finding-out-who-calls-jvm-shutdown-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!