How to get return code in shutdown hook
Asked Answered
B

2

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.

Bandur answered 9/2, 2017 at 2:45 Comment(4)
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.Bandur
what you want to do with original exit code as you want to set code base on your application result.Justifier
i am afraid that the original code is error code and I should not modify error code.Bandur
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?Rumen
J
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.

Justifier answered 9/2, 2017 at 4:5 Comment(0)
R
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

            }
    }

}
Rumen answered 9/2, 2017 at 4:51 Comment(3)
Could fail if there is a mechanism to catch and log exceptions in between.Christ
I guess it could work if you directly extend Throwable rather than Exception.Christ
It would have to be extends Throwable since those are rarely caught. I will post a little snippet in a secRumen

© 2022 - 2024 — McMap. All rights reserved.