3

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?

Laures
  • 5,389
  • 11
  • 50
  • 76

3 Answers3

6

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);
}
}
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • I don't understand this answer. The OP's problem is not that the shutdown hooks don't run. It is that the JVM doesn't exit. – Stephen C Oct 06 '11 at 09:10
  • it was quite helpfull, i wasn't aware of some strange hooks that blocked the shutdown. – Laures Oct 30 '11 at 17:56
3

One possibility is that the call to System.exit(...) throws a SecurityException.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

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.

Kai
  • 700
  • 7
  • 33