The solution to the servlet thread safety problem

Source: Internet
Author: User

One, how the servlet container handles multiple requests at the same time.

The servlet uses multithreading to handle multiple requests at the same time, and the Servelet container maintains a line pool service request.
The thread pool is actually a set of threads waiting to execute code called worker threads (worker thread), and the servlet container uses a dispatch thread to manage worker threads (Dispatcher thread).

When the container receives a request to access the servlet, the dispatcher thread selects a worker thread from the thread pool, passes the request to the thread, and then executes the servlet's service method by that thread.
When this thread is executing, the container receives another request, and the dispatcher thread selects another worker thread from the pool to serve the new request, and the container is not related to whether the request accesses the same servlet or another servlet.
When the container receives multiple requests to the same servlet at the same time, the service method of the servlet is executed concurrently in multi-threading.

Second, the servlet container defaults to single-instance multithreading to handle requests, which reduces the overhead of generating servlet instances and increases response time to requests. For Tomcat you can set the number of threads in the thread pool through the <Connector> element in Server.xml.

As far as implementation is concerned:
The responsibility of the dispatcher thread class, such as its name, is that the responsibility of the class is to dispatch the thread, only to use its own attributes to fulfill its responsibilities. So the class is responsible, and the responsibility of the class is concentrated in the only single object.
While other objects depend on the responsibility of that particular object, we need to get that particular object. That class is the implementation of a singleton pattern.

Third, how to develop a thread-safe servlet
1, variable thread safety: variables here refer to fields and shared data (such as form parameter values).

A, localize the parameter variables. Multithreading does not share local variables. So we want to use local variables in the servlet as much as possible.
For example: String user = "";
user = Request.getparameter ("user");

B, use synchronous block synchronized to prevent code blocks that might be called asynchronously. This means that threads need to be queued for processing.
When using the same plate to minimize the scope of the synchronization code, do not directly in the Sevice method and response methods to use synchronization, which can seriously affect performance.

2, properties of thread-safe: servletcontext,httpsession,servletrequest Objects in properties
ServletContext: (thread is not secure)
ServletContext is a multithreaded simultaneous read/write attribute, threads are unsafe. You want to synchronize the read and write properties or Deep Clone ().
Therefore, in the context of the servlet, as little as possible to save the modified (write) data can be used in other ways to share in multiple servlets, for example, we can use a singleton mode to process the shared data.
HttpSession: (thread is not secure)
The HttpSession object exists during a user session and can only be accessed in a thread that processes requests that belong to the same session, so the session object's property access is theoretically thread-safe.
When a user opens multiple browser windows that belong to a process, in which the access is in the same session, multiple requests are made and multiple worker threads are required to process the request, which can result in simultaneous multithreaded read and write properties.
At this point we need to synchronize the reading and writing of the properties: using the synchronization block synchronized and using a read/write to resolve.

ServletRequest: (thread is secure)
For each request, executed by a worker thread, a new ServletRequest object is created, so the ServletRequest object can only be accessed in one thread. ServletRequest is thread-safe.
Note: The ServletRequest object is valid within the scope of the service method and does not attempt to persist a reference to the request object after the service method ends.

3, use a Synchronized collection class:
Using vectors instead of ArrayList, use Hashtable instead of HashMap.

4, do not create your own thread in the servlet to complete a function.
The servlet itself is multithreaded, and creating threads in the servlet will complicate execution and lead to multithreading security issues.

5, in multiple Servlets for external objects (such as files) to modify the operation must be locked, to achieve mutually exclusive access.

Quad, Singlethreadmodel interface
The Javax.servlet.SingleThreadModel interface is an identity interface, and if a servlet implements this interface, the servlet container will ensure that only one thread can execute in the service method of a given servlet instance at a time. All other requests are queued.
Servers can use multiple instances to handle requests, instead of the benefits of a single instance of request queuing. The server creates an instance pool of multiple servlet instances of the servlet class, responds to each request-allocation servlet instance, and then puts it back into the instance pool to wait for the request. This creates a problem with concurrent access.
Local variables (fields) are also safe at this point, but are not secure for global variables and shared data and require synchronous processing. For such a multi-instance scenario, the Singlethreadmodel interface does not solve the concurrency access problem.

The Singlethreadmodel interface has been deprecated in the servlet specification.

The servlet architecture is built on the Java multithreading mechanism, whose life cycle is the responsibility of the Web container.

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.

There are also many ways to solve this class

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.


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:


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.

The above three methods are tested to show that they can be used to design a thread-safe servlet program. However, if a servlet implements the Singlethreadmodel interface, the servlet engine will create a separate servlet instance for each new request, which will cause a lot of overhead. Singlethreadmodel is no longer advocated in Servlet2.4, and the performance of the system can be greatly reduced if synchronization is used in the program to protect the shared data to be used. This is because the code block that is being synchronized can only have one thread executing it at the same time, making it handle the throughput of customer requests at the same time, and many customers are in a blocking state. In addition, in order to ensure the consistency of the contents of main memory and the data of the thread, the cache can be refreshed frequently, which will greatly affect the performance of the system. Therefore, in the actual development should also avoid or minimize the synchronization code in the servlet, in Serlet to avoid the use of instance variables is the best choice to ensure that the servlet thread security. From the Java memory model It is also known that the temporary variables in the method are allocated space on the stack, and each thread has its own private stack space, so they do not affect the thread's security.


A servlet's thread-safety problem is only apparent when there is a lot of concurrent access, and it is difficult to find, so pay special attention when writing a servlet program. Thread-safety issues are primarily caused by instance variables, so you should avoid using instance variables in Servlets. If application design cannot avoid using instance variables, use synchronization to protect the instance variables to be used, but to ensure the best performance of the system, you should synchronize the code paths with the least available availability

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.