7

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.

Leslie Wu
  • 760
  • 3
  • 13
  • 29
  • but how to know the original exit code in main thread. What if it should be -1 but I set it to 1 in shutdown hook. – Leslie Wu Feb 09 '17 at 02:55
  • what you want to do with original exit code as you want to set code base on your application result. – ravthiru Feb 09 '17 at 03:16
  • i am afraid that the original code is error code and I should not modify error code. – Leslie Wu Feb 09 '17 at 03:19
  • I deleted my comment because it was clearly wrong but if if this is your app knowing when to exit shouldn't be hard. Why don't you create an special Throwable (to bypass catch (Exception...)) to be caught in the main method? Then change/shutdown accordingly without hooks? – bichito Feb 09 '17 at 04:41

2 Answers2

5

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.

ravthiru
  • 8,878
  • 2
  • 43
  • 52
0

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

            }
    }

}
bichito
  • 1,406
  • 2
  • 19
  • 23