Tim Holloway wrote:servlet requests should be processed as fast as possible. There are only a limited number of threads in the processing pool and while the servlet is handling a GET, POST, or other HTTP request, it's using one of those threads.
Officially, the request should neither block nor spawn child threads. In reality, a certain limited amount of blocking does occur - for example, while a JDBC operation is in progress, or when a servlet makes an internal URL connection for a web service on an external server. However, if the request is expected to take a long time, it should be transferred to a non-servletrequest thread so that the request thread can be freed up.
Tim Holloway wrote:...
I normally use what I call a "null servlet" for long-term processes. A Null servlet is simply a servet that has an init() method, but no doGet/doPost methods. It's not essential that the null servlet avoid implementing doGet/doPost, but usually it's cleaner that way. The servlet is configured to start at webapp initialization time instead of on-demand.
In the init() method, you're not running under a request thread, so you can spawn threads of your own. Generally what I spawn is "engine" threads, which work with a queue of requests which are added and monitored using servlet requests. However, you can spawn a custom network server thread(s) as well.
You should also code an onDestroy method so that this thread(s) are informed when the server is shutting down so that they may clean themselves up and terminate. If you don't then Tomcat will complain and/or hang on shutdown (waiting for all threads to terminate).