Sometimes, tomcat restart will cause my application stop immediately so that my consuming data in oracle db keep one error state. So I want know if has any methods to help handling the state once the tomcat stop. Due to unknown the actual events happen on the stop procedure of tomcat. I can't know how to make sure something happen when tomcat stopped.
Asked
Active
Viewed 1,866 times
2 Answers
2
If you are doing a normal restart you should be able to register a shutdownhook and have it run before the server kills the app.
Check out the javadocs for more detailed info: http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread).
You can add a shutdown hook like this:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
public void run() {
// clean-up logic
}
}));

Paul Cichonski
- 388
- 1
- 6
-
Thanks. I have another issue: when tomcat stop. if the shutdown of all thread is through thread.interrupt. If so. I can judge interrupted state to make sure something done? – jiafu Jun 12 '12 at 01:58
-
I'm not sure that I fully understand your question. There are a few different ways that the thread can be stopped. A Kill -9 is very different than a graceful shutdown of the server. This answer provides a ton of details: http://stackoverflow.com/a/2541618/1442761. – Paul Cichonski Jun 12 '12 at 02:04
-
maybe I hadn't explain it clearly. My mean is what influences on existed running thread when stop jvm. Many thanks to you! – jiafu Jun 12 '12 at 02:13
2
Perhaps you can register a LifecycleListener
for your tomcat application (link). A lifecycle listener will be called when your context is loaded and right after it is being closed.
Here is a more involved explanation link. You might want to look at the contextInitialized
and contextDestroyed
methods of the ServletContextListener
interface.

Ricardo Marimon
- 10,339
- 9
- 52
- 59
-
Thanks. I have another issue: when tomcat stop. if the shutdown of all thread is through thread.interrupt. If so. I can judge interrupted state to make sure something done? – jiafu Jun 12 '12 at 01:58
-
1On the `contextDestroyed` method you can actually stop the threads. You just have to keep track of the threads you start in `contextInitialized`. – Ricardo Marimon Jun 13 '12 at 02:38