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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With