Creating threads a Webapplication which is deployed in Tomcat Creating threads a Webapplication which is deployed in Tomcat multithreading multithreading

Creating threads a Webapplication which is deployed in Tomcat


The restriction on creating threads in a container was really just a suggestion to keep inexperienced developers from shooting themselves in the foot. No container actually prohibits you from doing this. With java.util.concurrent classes, creating threads should be less error prone and I wouldn't worry about this restriction too much.

If your requirements are simple, it's easy enough to just create a single thread / runnable in a ServletContextListener. Create and start the thread in contextInitialized() and shut it down in contextDestroyed(). . Use a ScheduledExecutorService created by Executors.newSingleThreadScheduledExecutor(). The Runnable you pass to the Executor would read from a BlockingQueue.

If your requirements change and you need something more complicated, you probably want to looks at JMS / MDBs or a scheduler like Quartz.


You could use a scheduler to run jobs regularly or use the Spring equivalent of Message Driven Beans (some documentation on JMS and Spring) which are executed by the container which does the queue polling for you.


You can try using Spring 3.x asynchronous method invocation. Caller method will return immediately and the actual execution happens asynchronously

applicationContext:

<task:annotation-driven executor="asyncExecutor" mode="aspectj"/><task:executor id="asyncExecutor" pool-size="${executor.poolSize}"/>

On your bean:

@Asyncpublic void sendEmail(...) { // ...}

please refer to Spring documentation for further details: Spring 3.x Task Execution and Scheduling