Occasional InterruptedException when quitting a Swing application

前端 未结 17 1125
心在旅途
心在旅途 2020-12-05 04:55

I recently updated my computer to a more powerful one, with a quad-core hyperthreading processor (i7), thus plenty of real concurrency available. Now I\'m occasionally

17条回答
  •  失恋的感觉
    2020-12-05 05:17

    It sounds like you have a thread running which hasn't terminated when you quit. Notably, the thread is wait()ing, and that method throws an interrupted exception if you try to stop the thread while it's running. I always set background threads to run as Daemons, which might help as well.

    I would do the following in your JFrame:

    myJFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        // Some pieces of code to instruct any running threads, possibly including
        // this one, to break out of their loops
    
        // Use this instead of System.exit(0) - as long as other threads are daemons,
        // and you dispose of all windows, the JVM should terminate.
        dispose();
      }
    });
    

    By manually breaking out of the loop, you allow the wait method to terminate (hopefully you're not waiting terribly long, are you? If you are, you might want to re-examine how you're utilizing your threads) and then get to a point in your code where it's safe to break - safe because you coded it to do so - and then the thread will terminate, letting the application terminate just fine.

    Update Perhaps you are using the event dispatch thread inappropriately somewhere, and it's waiting/still working for you when you try to exit? The dispatcher thread should be doing as little work as possible, and should be passing anything complex off to another thread as quickly as it can. I'll admit I'm stabbing around in the dark a little bit, but I'm inclined to think it's not a bug, especially considering that you started noticing it on a more powerful machine - which to me screams "Race Condition!" not Java bug.

提交回复
热议问题