JVM在System.exit(1)后仍可存活

3

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

为什么jvm在调用system.exit后没有关闭呢?

3个回答

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);
}
}

我不理解这个答案。OP的问题不是关闭挂钩没有运行,而是JVM没有退出。 - Stephen C
这非常有帮助,我之前不知道一些奇怪的钩子会阻止关机。 - Laures

3

一个可能性是调用System.exit(...)时抛出了SecurityException异常。


2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接