Laures Laures - 3 years ago 218
Java Question

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.exit is called?

Answer Source

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);
}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download