Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if System.exit() is called again while a JVM shutdown is already in progress?

Is it no-op? Does the JVM avoid calling the shutdown hooks again?

For a use case, consider an UncaughtExceptionHandler that calls System.exit() for SomeException and then SomeException is thrown in two separate threads within a short period of time.

Also, assume that System.exit() is called in a new thread to avoid potential deadlocks.

UPDATE

As one of the comments rightfully pointed out, I should have tested this myself but I was lazy. The test below completes successfully irrespective of whether System.exit() is called in a regular or daemon thread and exits with code 1 after printing:

Requesting shutdown ...
Shutdown started ...
Requesting shutdown ...
Shutdown completed ...

And here is the code:

public class ConcurrentSystemExit {

  private final static boolean DAEMON = false;

  public static void main(String[] args) throws InterruptedException {

    // Register a shutdown hook that waits 6 secs
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        try {
          System.out.println("Shutdown started ...");
          Thread.sleep(6000);
          System.out.println("Shutdown completed ...");
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });

    // Define a Thread that calls exit()
    class ShutdownThread extends Thread {
      public void run() {
        System.out.println("Requesting shutdown ...");
        System.exit(1);
      }
    }

    // Issue first exit()
    Thread t1 = new ShutdownThread();
    t1.setDaemon(DAEMON);
    t1.start();

    Thread.sleep(3000);

    // Issue second exit()
    Thread t2 = new ShutdownThread();
    t2.setDaemon(DAEMON);
    t2.start();
  }
}
like image 872
Bogdan Calmac Avatar asked Nov 05 '13 20:11

Bogdan Calmac


1 Answers

From the JavaDoc on Runtime.exit():

If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely. If shutdown hooks have already been run and on-exit finalization has been enabled then this method halts the virtual machine with the given status code if the status is nonzero; otherwise, it blocks indefinitely.

like image 80
Dolda2000 Avatar answered Oct 27 '22 19:10

Dolda2000