• Post Reply Bookmark Topic Watch Topic
  • New Topic

Running a thread in tomcat application

 
Abhilash
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I have to implement a thread in my TOMCAT application for an alert purpose. I have to run this thread automatically when the application starts in the server. How can i do it? Please help me.

Abhilash AT
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Warning: J2EE is usually not crazy about threads being launched by programmers (J2EE prefers the container to manage them). For one thing, such threads won't do well on clustered environment. Also, they might have trouble accessing some shared resources (e.g. consider a DataSource with container-managed transactions ).

2. Still, if you're not concerned with the above issues, you can define a ServletContextListener. In a nutshell, it means:
- You define a method ("contextInitialized") to be executed when the application starts up (in your case, it can start the thread)
- You define a method ("contextDestroyed") to be executed when the application shuts down (in your case, cause the thread to stop).
- You register your listener in "web.xml".

3. BTW, some web tutorials might suggest that you use Servlet.init() instead. Personally, I wouldn't do that (mamy things can go wrong with that approach).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!