Tomcat: Terminating threads spawned inside request-thread when HTTP connection is closed Tomcat: Terminating threads spawned inside request-thread when HTTP connection is closed multithreading multithreading

Tomcat: Terminating threads spawned inside request-thread when HTTP connection is closed


a.) the thread keeps running. when/if it eventually returns soemthing, it will fail with a socket exception, because the connection it is trying to write to is already closed. in plain servlet api, you have no way of telling the thread when the connection has been closed.

b.) if you spawn extra threads, an easy way to watch them is to use Callables and Futures from the java concurrency package. this gives you a convenient way of dealing with timeouts. check the documentation here:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html

and here:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html

anyway, you will be responsible for watching the threads and make sure they don't keep running forever, your servlet container will not do that for you.


Tomcat has a property called minSpareThreads. The unused thread will get destroyed unless it is within the minSpareThreads.

minSpareThreads
The minimum number of threads always kept running. If not specified, the default of 10 is used.

In the case of HTTP connection close , how to terminate/kill these threads spawned inside the request-thread?

There are various ways this can be done. First its important to note that under normal Tomcat usage, a Servlet processing a request, you will not be notified about the connection closing. But Tomcat does have advanced IO features that may be used to intercept the connection close if Tomcat treats it as an error and sends you the CometEvent mentioned in that link (requires further testing).

So now lets say you are either done waiting for the threads to finish (timed out) or you get a connection close notification through some means, then you would have to interrupt your worker threads (that you are trying to halt). This is typically done in two steps. 1) Set a shared atomic or volatile boolean object to a value that depicts "stop processing", a control flag of sorts. 2) Then interrupt your thread. The worker thread should break out of any blocking method and can then check if the shared variable (control flag) is set to "stop". You can skip step 1 if your worker thread naturally stops on its own after one iteration of some code. Some threads remain in a loop until their control flag is set to "stop". If you are using ExecutorService then its shutdownNow method will typically send a Thread.interrupt to all threads running in its pool.