JVM survives System.exit(1)
I'm currently maintaining a system that shuts down in case of failure by using system.exit(1). Unfortunately the java process of the system is still there when this happens.
How is it possible that a jvm doesn't shut down when system.开发者_如何学Cexit is called?
That's because System.exit(1)
doesn't shutdown hooks, use System.exit(0);
.
In fact, the System.exit(1)
does "Stall and halt", according to this code:
/* Invoked by Runtime.exit, which does all the security checks.
* Also invoked by handlers for system-provided termination events,
* which should pass a nonzero status code.
*/
static void exit(int status) {
boolean runMoreFinalizers = false;
synchronized (lock) {
if (status != 0) runFinalizersOnExit = false;
switch (state) {
case RUNNING: /* Initiate shutdown */
state = HOOKS;
break;
case HOOKS: /* Stall and halt */
break;
case FINALIZERS:
if (status != 0) {
/* Halt immediately on nonzero status */
halt(status);
} else {
/* Compatibility with old behavior:
* Run more finalizers and then halt
*/
runMoreFinalizers = runFinalizersOnExit;
}
break;
}
}
if (runMoreFinalizers) {
runAllFinalizers();
halt(status);
}
synchronized (Shutdown.class) {
/* Synchronize on the class object, causing any other thread
* that attempts to initiate shutdown to stall indefinitely
*/
sequence();
halt(status);
}
}
One possibility is that the call to System.exit(...)
throws a SecurityException
.
see also https://stackoverflow.com/a/19823373/812093 for a possible solution. The idea is basically to trigger System.exit in a separate thread and not in your main thread.
精彩评论