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
blockYou 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]
Did you still have to call System.exit(0) ? I had to, or my process never exited, despite these changes.
ReplyDelete