How to get return code in final mode

I need to change the JVM return code according to the result of my application.

But it is risky to explicitly call System.exit (code), because the application is complex, and it is difficult to determine the end of executable threads.

So, I came up with using hookdown to change the return code before the JVM exits.

But there is a problem that, as I can get the JVM coz source code, it could be an error code, not 0.

+7
java shutdown shutdown-hook
source share
2 answers

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

According to > JavaDoc

If this method is called after the virtual machine starts turning off the sequence, then if the hooks for stopping this method are started, it will be blocked indefinitely.

You do not have access to status , as it can change even after calling all exits.

+5
source share

Since shutdown errors and exit status are incompatible, you can 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 save the 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 } } } 
+1
source share

All Articles