JVM幸存下来System.exit(1)

时间:2011-10-06 08:17:49

标签: java

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

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

3 个答案:

答案 0 :(得分:5)

那是因为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);
}
}

答案 1 :(得分:3)

一种可能性是对System.exit(...)的调用会引发SecurityException

答案 2 :(得分:1)

另请参阅https://stackoverflow.com/a/19823373/812093了解可能的解决方案。这个想法基本上是在一个单独的线程中而不是在主线程中触发System.exit。