How to get return code in shutdown hook

半腔热情 提交于 2019-12-23 08:54:29

问题


I need to modify JVM return code according to my application result.

But it is risky to explicitly call System.exit(code) coz the application is complicated and it is hard to identify the end of running threads.

So I come up with using shutdown hook to modify the return code before JVM exit.

But there is a problem that how can I get the original return code of JVM coz it may be an error code not 0.


回答1:


You should not call exit method in shutdown hook, System.exit(status) internally calls Runtime.getRuntime().exit(status); which will cause your application to block indefinitely.

As per the JavaDoc

If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely.

You don't have access to status, as it could change even after all shutdown hooks are called.




回答2:


Since shutdown hooks and exit status are incompatible, you could create a Throwable whose only function is to be caught in the main method. Then the catch block becomes your shutdown block. There you can call System.exit() and even keep your shutdown code if you want.

class Emergency extends Throwable{
    int exit = 0;
}

public final class Entry {

    public static void main(String[] args){
            try {
                throw new Emergency();
            } catch (Emergency e) {
                // Shut down the app

            }
    }

}


来源:https://stackoverflow.com/questions/42127345/how-to-get-return-code-in-shutdown-hook

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