System.exit is not thread-safe on Linux?

怎甘沉沦 提交于 2019-12-05 05:57:49

It depends, the runHooks method will start any hook threads registered through Runtime.addShutdownHook and wait for them to be finished. If any of your hook threads is locking some resources that the AWT event thread is requiring too, they may cause dead lock.

If you have to call System.exit in your AWT event thread,I suggest you call it in another thread like:

 new Thread(){
            public void run() {
                System.exit(0);
            }
   }.start();

It is impossible to say whether this is a bug in the runtime without knowing more about what the application is doing (ideally, this would take the form of an SSCCE).

For example, the following demonstrates a similar deadlock involving System.exit(). However, it is clearly a bug in the application, not in System.exit():

public class OhNo {

    final static Object lock = new Object();

    public static void main(String[] args) {
        new Thread(new Runnable() {
            public void run() {
                synchronized (lock) {
                    for (;;) {
                    }
                }
            }
        }).start();
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                synchronized (lock) {
                    System.out.println("in shutdown hook");
                }
            }
        }));
        System.out.println("about to call System.exit()");
        System.exit(0);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!