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).