问题
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