JVM幸存下来System.exit(1)

Lau*_*res 3 java

我目前正在使用system.exit(1)维护一个在发生故障时关闭的系统.不幸的是,当发生这种情况时,系统的java进程仍然存在.

调用system.exit时jvm怎么可能没有关闭?

Buh*_*ndi 6

那是因为System.exit(1)不关闭钩子,使用System.exit(0);.

事实上,System.exit(1)根据这段代码,它会"停止并停止":

/* 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);
}
}
Run Code Online (Sandbox Code Playgroud)