Creating Threads on Tomcat Deployment
If you want to start a thread in an application server when your application is deployed (such as creating a thread to regularly monitor or analyse data that was submitted to a database, or to open up a port to accept UDP packets) where would you create it?
does anyone know any resources that might point me to the right way to do this?
Thanks,
Jacob
(NB: I am suspect that by default security managers probably don't allow web apps to do things such as create their own ports)
[510 byte] By [
JLina] at [2007-11-26 13:52:31]

Create a servlet as normal, put the thread startup code in the init method of the servlet, and specify that the servlet should run on startup in the web.xml file
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>com.acme.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
The official way to do this kind of thing is to use a LifecycleListener, which is a class implementiing the LifecycleLisetener whose FQN you supply in the server.xml config file. You can put these listeners in at various levels of the container, at the server or individual web-app level.
In fact, by default, Tomcat runs without a security manager - the default assumption is that you wrote the web-app code yourself and, hence, trust it.
If you need to run with a security manager then you are going to have to tweak the policy file a fair bit anyway, to get all you database and file access working. I had to do this, once, to enable RMI calls from servlets.
(As I recall the policy file is in the tomcat configuration directory).
ps.
Don't forget if you start a thread inside Tomcat you need to think about how it will terminate. If you don't make set it to daemon mode, or close it explicitly from a life cycle listener it may prevent Tomcat from being closed down cleanly.
Message was edited by:
malcolmmc