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 an increased counter value 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 matches this request with a special instance created by the server.

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

+6
source share
1 answer

A servlet instance is created when you start your webapp or when it is required first (if lazy-init is installed). It is deleted when your webapp stops when it is GCed. In a normal production environment, I would dare to state that this never happens (apart from deploying the new version).

Most (if not all) servlet containers work with a thread pool. This means that they reuse threads to process requests. Therefore, these threads never die; they return to the pool when they complete the request.

Of course, they die when you close the server :)

From the point of view of your application, you really should try to make your servlet standstill, and you can safely assume that each request is executed in its own dedicated thread.

+4
source

Source: https://habr.com/ru/post/907248/


All Articles