The life cycle of servlet is generally:
1. Establize the servlet
2. Process zero or more requests from the client
3. Destroy the servlet, GC Recycling Occupation Memory
Each Server may have different methods on how to support servlets, but the above servlet lifecycle is the rules that each servlet engine must comply.
Instance Holding Instance Persistence:
Once a servlet instance is loaded, start processing all the requests to this servlet, in other words, a servlet generates only one instance. Such a practice is very good for performance improvement, and can effectively reduce system overhead, and also effectively achieve persistence (such as database connections, cache data).
import java.io *;. import javax.servlet *;. import javax.servlet.http *;. public class SimpleCounter extends HttpServlet {int count = 0; public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {res .setContentType ("text / plain"); PrintWriter out = res. max ; out.println ("Since Loading, this Servlet Has Been Accessed Count " Times. ");}} Simplely reflects examples of Servlet persistence, each request adds local variable count, then prints the display. However, there is a multi-thread risk in the previous example. It can be seen as a thread object for each request to access the servlet, and they all access the same servlet instance, so there will be concurrent problems. In particular, there is a greater risk when there is a read / write operation of the shared variable (for example, the local variable count of the above case).
The solution is to increase the SYNCHRONIZED block.
PrintWriter out = res. maxchronized (this) {count ; out.println ("Since Loading, this Servlet Has Been Accessed Count " Times. ");}
In fact, all the registration names of each servlet correspond to an instance of the servlet, and use the request name to access the servlet to determine which instance is to process the request.
Servlet Reloading