Friday, April 18th, 2008

Patrick & Avi's Java Tips #2: Graceful JVM Shutdown in Eclipse

By Avi Flax

If your Java application has any Shutdown Hooks, you probably want them to run every single time you stop your app – even when it’s running within Eclipse. Unfortunately, when you click the red “Terminate” button in Eclipse, it kills the JVM process abruptly; Shutdown Hooks don’t have a chance to run.

<p>Here’s my approach to this problem:

  1. Add an environment variable to your run configuration, in the Environment tab. I call it RUNNING_IN_ECLIPSE, I like to be super-explicit. Set its value to TRUE.
  2. Add this block to the bottom of main():
    /* a hack to make sure that our shutdown hooks get called from within eclipse */
    if (Boolean.parseBoolean(System.getenv("RUNNING_IN_ECLIPSE")) == true)
    {
    System.out.println("You're using Eclipse; click in this console and
    press ENTER to call System.exit() and run the shutdown routine.");
    System.in.read();
    System.exit(0);
    }
    

As the code says: from now on, any time you run your app using this run configuration, the console will listen for input, blocking. As soon as you click in the console to give it focus and press enter, the next line will call System.exit(0), which will tell the JVM to gracefully shut down, which includes calling your shutdown hook.

One Response

  1. Roy said:

    Cool hack. Thank you.

Leave a Comment