6

What I want is to start a thread every time the tomcat server starts.For this I need to catch the event of shutting down of tomcat.How can I do this?I tried to do it using sessions but sometimes the session even persists after shutting down and restating tomcat?what are my options?

5
  • 2
    What are you trying to do? Commented Jul 16, 2014 at 15:21
  • If you want to do something on startup, why are you looking for shutdown events? That doesn't make sense to me. This seems like an XY Problem. Commented Jul 16, 2014 at 15:23
  • sometimes the session even persists I don't think so. How are you validating it? Commented Jul 16, 2014 at 15:25
  • 2
    You can't get tomcat shutdown process, but you can get the process when your web application is being undeployed or shut down using ServletContextListener. Commented Jul 16, 2014 at 15:27
  • 1
    What I am trying to do is run a thread through a jsp page on startup..but I don't want multiple instance of that thread everytime the jsp page is visited.for that I thought the best solution would be to run the thread only when the tomcat starts ..if I know that tomcat has been shutdown and started again then I have to start the thread..that's why the question.. Commented Jul 16, 2014 at 15:45

1 Answer 1

12

You can try to catch an JVM shutdown event in this way:

 Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("BYE BYE"); } }); 

The other option is to implement ServletContextListener by using @WebListener Annotation. No xml configuration is required in this case.

@WebListener public class MyLifeCycleListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { //TODO ON START } public void contextDestroyed(ServletContextEvent event) { //TODO ON DESTROY } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.