Monday, April 01, 2013

Gracefully Shutting Down Spring Applications

To gracefully shutdown your spring (non-web) application, you should do two things:

1. Register a shutdown hook
Call registerShutdownHook() that is declared in the AbstractApplicationContext class in order to register a shutdown hook with the JVM. I wrote about Shutdown Hooks in a previous post. They allow your application to perform "clean up" when the JVM exits either naturally or with a kill/Ctrl+C signal. Spring's shutdown hook closes your application context and hence calls the relevant destroy methods on your beans so that all resources are released (provided that the destroy callbacks have been implemented correctly!). Also, note that no guarantee can be made about whether or not any shutdown hooks will be run if the JVM aborts with the SIGKILL signal (kill -9) on Unix or the TerminateProcess call on MS Windows.

2. Close the context in a finally block
You should also call close() on your application context in a finally block. This is because if your application throws an unhandled RuntimeException, you might have background threads, started by some beans, still running and your JVM will not terminate. That's why you need to explicitly close the application context.

Putting these two steps together, you get the following code:

public static void main(final String... args) {
  AbstractApplicationContext appContext = null;
  try {
    appContext = new AnnotationConfigApplicationContext("my.app.package");
    appContext.registerShutdownHook();
    final MyApp app = appContext.getBean(MyApp.class);
    app.doSomething();
  } catch (final Exception e) {
    // handle exceptions properly here
    e.printStackTrace();
  } finally {
    if (appContext != null) {
      ((AnnotationConfigApplicationContext) appContext).close();
    }
  }
}
Related Posts:
Shutting Down Java Apps [Howto]

1 comment:

  1. Did you still have to call System.exit(0) ? I had to, or my process never exited, despite these changes.

    ReplyDelete