I need to create a thread that listens to a filepath for new, modified or removed files. I am using a web application that uses Spring 3, Struts 2 and Hibernate 3. If I run the project, it loads the index.jsp which contains the text "Hello World".
The problem is that when I create a java Thread() that listens to the filepath and assign it to index.jsp:
index.jsp
Then "Hello World" text does not ever appear because the Thread doesn't ever stop (Which is right, it's not supposed to stop). I need this Thread to be running in the background and not interfere with the rest of the web application. I don't want to create a separate web application just for this Thread though. Also, I don't want a new Thread instance to be created each time a new Session instance is created, there should be just one Thread instance no matter how many Session instances there are active.
解决方案
Basically, people will suggest not to start your own thread in a container managed application, like a web application or an enterprise (EJB) application.
This is because in a container environment all the resources including threads should be managed by container. But IMHO if you know the implications, and the life cycle of our own thread and its resources, like wrapping this thread with a transaction etc, then we can create a thread by using the standard way (new Thread()), but it is just my opinion.
I would suggest you to go through the 'Container managed threads' once before you make a decision. You can refer commonJ once to get a handle to Container's thread pool, but as this is not a standard or not mentioned in the container specifications, It may not work for all the containers. This will work for: