Search code examples
javaswingevent-dispatch-threadshutdown-hook

Detecting that JVM is shutting down


I have a Swing application that handles Ctrl+C using addShutdownHook(), and it works fine until one of the shutdown tasks I have calls a function that under normal circumstances changes a JLabel text, at which point it hangs.

I assume the problem is that the Swing EDT has either terminated or is waiting for something.

Is there a way to either determine that the EDT has terminated or is "done" (so I can avoid calling Swing methods), or to prevent the usual close-all-the-windows-down behavior on Ctrl-C?


Just to clarify:

I have a method in a class called stop(). Under normal circumstances this can get called (along with its complement start()) and it triggers a cascade of things that causes a JLabel to be updated, for visual feedback that a stop() has occurred.

When my shutdown hook runs, I need to call stop() to gracefully shutdown some resources.

What I'm asking is how I can detect that Swing EDT is not there, so I can rewrite stop() so that it detects a lack of Swing and avoids the call to the Swing functions.


Solution

  • I ended up setting a flag at the beginning of the shutdown hook, and communicating this (via objects set up ahead of time) to the object with my stop() method, so that it can test this flag and decide whether or not to call the Swing methods.

    If the shutdown flag is not set, the Swing methods get called. Otherwise they don't.