这是不操作吗?JVM会避免再次调用关闭挂钩吗?
对于一个使用案例,考虑一个UncaughtExceptionHandler,它为SomeException调用System.exit(),然后在短时间内在两个单独的线程中抛出SomeException。
此外,假设在新线程中调用System.exit()以避免潜在的死锁。
更新
正如其中一条评论正确指出的那样,我应该自己测试,但我太懒了。下面的测试无论是在常规线程还是守护线程中调用System.exit()都可以成功完成,并在打印后以代码1退出:
Requesting shutdown ...
Shutdown started ...
Requesting shutdown ...
Shutdown completed ...
这里是代码:
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();
}
}