Reputation: 8283
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();
}
}
Upvotes: 7
Views: 1488
Reputation:
Just for your info, exit() method can throw SecurityException.
Throws: SecurityException - if a security manager exists and its checkExit method doesn't allow exit with the specified status.
What happens if System.exit() is called again while a JVM shutdown is already in progress?
It depends on the security context, but in majority of cases nothing is executed after a call to the exit method, it just terminates the JVM.
Upvotes: 0
Reputation: 25855
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.
Upvotes: 5