In production environments, JVMs are killed and restarted either automatically by network management systems or manually by a network administrator. When a JVM is killed, it is often necessary to perform some cleanup work before the JVM finishes shutting down.
Intercepting JBoss AS shutdown can be useful in some circumstances, for example if you want to make sure that some housework is performed before shutting down. Here we will show some examples some of which are portable also on other containers.
Intercepting JBoss AS shutdown can be useful in some circumstances, for example if you want to make sure that some housework is performed before shutting down. Here we will show some examples some of which are portable also on other containers.
A shut down hook is simply a Thread that is registered with the JVM and run just before the JVM shuts down. You can add it to any Class that is instantiated by your container. In this example we will add it to the init() method of a Servlet which is registered as startup Servlet.
And here is its mapping:
Here, the critical piece of code is in the init() method which registers the Shutdown hook on the class MyShutDown.
MyShutdown sh = new MyShutdown(this);
Runtime.getRuntime().addShutdownHook(sh);
The run() method in the Class MyShutdown will be fired as soon as shutdown kicks in and recalls the method freeResources from the Servlet.
MyShutdown sh = new MyShutdown(this);
Runtime.getRuntime().addShutdownHook(sh);
The run() method in the Class MyShutdown will be fired as soon as shutdown kicks in and recalls the method freeResources from the Servlet.
This approach is less portable since it requires extending the ServiceMBeanSupport Class which exposes JBoss MBeans lifecycle methods.
Here, when the shutdown sequence gets started, and before the MBean deployed is evicted from memory, the stopService method is invoked, which cares to free resources.
Approach #3 Use @PreDestroy annotation to clean the house
If you application uses EJB to handle resources which need to be evicted at shutdown, then consider using the @PreDestroy annotation as a "finalizator".
The destroy method will kick in as soon as the bean is being allocated, including JBoss shutdown.
Just a word of caution: I've tested this one on JBoss successfully but it's not guaranteed to work the same on other application servers- but you don't want to switch to other AS, do you ?
Just a word of caution: I've tested this one on JBoss successfully but it's not guaranteed to work the same on other application servers- but you don't want to switch to other AS, do you ?












