Java – Thread in servlet

javamultithreadingservlets

In an application if there are multiple servlets involved then is everytime a new thread is created for a different servlet

for ex i have 2 servlets servlet 1 and servlet 2 both are getting rquest from the same html form one is getting through anchor tag and another through form

when link is clicked request is sent to servlet one which dispatches request to index page again and from there the form is submitted where request is sent to servlet 2

so are 2 threads created each for servlet 1 and servlet 2 or only 1 thread is created which serves both servlets ??

Best Answer

The general pattern for a Servlet container is to use one Thread to handle one request.

for ex i have 2 servlets servlet 1 and servlet 2 both are getting rquest from the same html form one is getting through anchor tag and another through form

When you submit the form, the browser sends an HTTP request. Your server dispatches a Thread to handle it. Think of it doing something like this (it's much more complex in reality)

final Servlet servlet = ...// which servlet is url-mapped to the request
Runnable toRun = new Runnable(
    public void run() {
        servlet.service(request, response); // with exception handling of course
    }
);
Thread toDispatch = new Thread(toRun); // actually get it from pool, but for simplicity
toDispatch.start();

Again, if you follow an anchor link, your browser sends a new HTTP request that gets handled the same way.

The Servlet class instance is shared among threads.