duncanportelli
duncanportelli

Reputation: 3229

Multithreading inside Tomcat - Create a Thread Pool

I have a servlet which is used for a long process which takes minutes to complete. Upon receiving a request to this servlet, the long process is executed inside a thread in order to send the response back to the client immediately due to timeout issues:

public class TestServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        //Thread safe code
        Thread thread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(10000); //simulate long processing
                } catch(InterruptedException v) {
                }
            }  
        };

        thread.start();
    }

}

This means that every time I receive a request, a new thread is created. In order not to run into the risk of attacks, I need to control how many threads are allowed. This means having a pool in the context, and implementing a fail-fast if all threads are busy.

I was looking at the Executor interface. My question is, how can I implement this Thread Pool Executor to be accessible from all the requests received and act as a queue for all the threads? Should I declare the executor as a local non-thread safe variable in the servlet to be accessible by all instances of this servlet as shown below?

public class TestServlet extends HttpServlet {

    //non-thread safe variables
    //declare executor here

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        //instantiate executor in case it is null

        Thread thread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(10000); //simulate long processing
                } catch(InterruptedException v) {
                }
            }  
        };

        //add thread to the executor
    }
}

Or is it possible to declare this executor at context level?

I was looking also at the Tomcat Executor, which I believe is used by Tomcat itself to manage its thread. Would it be possible to also add these threads to this executor as well?

Upvotes: 2

Views: 1759

Answers (1)

Lew Bloch
Lew Bloch

Reputation: 3433

Usually doing explicit thread management in an app server is a bad idea. You could set up the servlet to run in a new thread itself, and thus avoid farming things out to another thread inside the servlet. I haven't looked up whether Tomcat lets you configure the maximum number of simultaneous instances of a servlet allowed, so that might remain an issue.

If you do explicitly use 'Thread.sleep()', don't abandon the 'InterruptedException' like that. It's the wrong thing to do. Look up the right thing (handle and re-interrupt).

Upvotes: 0

Related Questions