Life cycle:
The servlet architecture is built on the Java multithreading mechanism whose life cycle is the responsibility of the Web container in which it runs, specifically the servlet
1 instantiation (created)
2 Initializing init ()
3 Processing Request Service ()--doget () and,
4 Final destruction of the destory () process
Thread Safety:
When a client requests a servlet for the first time, the servlet container instantiates the Servlet class based on the Web. XML configuration file. When a new client requests the servlet, the servlet class is typically no longer instantiated, that is, multiple threads are using the instance. In this way, when two or more threads access the same servlet at the same time, multiple threads can access the same resource at the same time, and the data may become inconsistent, so it is easy to create a number of security issues.
Ways to resolve this problem:
1. Implement Singlethreadmodel interface
This interface specifies how the system handles calls to the same servlet. If a servlet is specified by this interface, then the service method in this servlet will not have two threads being executed concurrently, and there is no thread-safe issue, of course. This is the only way to inherit this interface.
public class XXXXX extends HttpServlet implements Singlethreadmodel {.....}
2. Synchronize the operation of the shared data
Using the Synchronized keyword ensures that only one thread can access the protected section at a time, and in this paper, the synchronization block operation can be used to ensure the thread safety of the servlet. The code after synchronization is as follows:
public class XXXXXX extends HttpServlet {.... synchronized (this) {XXXX}}
3. Avoid using instance variables
Some of the thread-safety issues are caused by instance variables, which are thread-safe as long as the instance variables are not used in any of the methods inside the servlet.
About the life cycle and thread security of the servlet