Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the instance created by the server die?

The following program :

public class SimpleCounter extends HttpServlet {

    int counter=0;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        PrintWriter writer = response.getWriter();
        counter++;
        writer.println("accessed " + counter + " times" );
    }
}

prints the incremented value of counter every time I access the url of this servlet. I read that the server creates an instance of this servlet and whenever there is a request for this servlet a new thread maps this request to the special instance created by the server.

When does the instance created by the server (to which thread maps the request) die? When do the threads created by a new request die?

like image 803
Suhail Gupta Avatar asked Jan 30 '12 16:01

Suhail Gupta


1 Answers

The servlet instance is created when your webapp starts, or when it is first required (if lazy-init is set). It is disposed of when your webapp stops, when it is GCed. In a normal production environment, I'd dare to state this never really happens (not counting deploying a new version).

Most (if not all) servlet containers work with a thread pool. This means they reuse threads to handle requests. So these threads never die; they return to the pool when they finish executing the request.

Of course, they do die when you shut down the server :)

From the standpoint from your application, you really should try to make your servlet stateless, and you can safely consider that each request is executed in its own dedicated thread.

like image 102
Joeri Hendrickx Avatar answered Oct 20 '22 19:10

Joeri Hendrickx