Multithreading and thread safety for Servlets

Source: Internet
Author: User

Thread Safety

Let's start with a discussion of thread safety, which we can call thread safety?
The explanation given in Java concurrency programming is that " when multiple threads access a class, regardless of how the runtime environment is scheduled, or how those threads will be executed alternately, and no additional synchronization or collaboration is required in the keynote code, this class can behave correctly. Then call this class thread-safe . "

the invocation process and life cycle of the servletthe life cycle of the servlet

The servlet is run in a servlet container, and the common Tomcat, JBoss, and WebLogic are servlet containers whose lifecycle is managed by the container. The life cycle of the servlet is represented by the Init (), service (), and Destroy () methods in the Java.servlet.Servlet interface. The life cycle of a servlet has four phases: load and instantiate, initialize, request processing, destroy.
Load and Instantiate
The servlet container is responsible for loading and instantiating Servelt. The servlet instance is created when the servlet container is started, or when the container detects that the servlet is needed to respond to the first request. When the servlet container is started, the servlet loads the servlet class through the ClassLoader and then initializes a new Servlet object to complete the instantiation.

Initialization
After the servlet is instantiated, the container calls the Init () method and passes the object that implements the ServletConfig interface. In the Init () method, the servlet can read configuration parameters in the deployment descriptor, or perform any other one-time activities. The init () method is only called once for the entire life cycle class of the servlet.

Request Processing
When the servlet is initialized, the container is ready to process the client request. When the container receives a request for this servlet, it invokes the servlet's service () method and passes the request and response objects as parameters. When a parallel request arrives, multiple service () methods can run concurrently in a separate thread. By parsing the ServletRequest or HttpServletRequest object, the service () method processes the user's request and invokes the Servletresponse or HttpServletResponse object to respond.

Destroyed
Once the Servlet container detects that a servlet is to be unloaded, it may be because the resource is being reclaimed or because it is being closed, the container will call the servlet's Destroy () method after all the service () threads of the servlet. The servlet can then collect cleanup for useless storage units. The Servlet object is then destroyed. These four phases collectively determine the life cycle of the servlet.

the invocation procedure of the servlet

1. The client sends a request to Tomcat,tomcat to send the client a request page to the client.

2. After the user has related actions to the Request page, the page is submitted to Tomcat,tomcat to encapsulate it as a HttpRequest object, and then the request is processed.

3.Tomcat intercepts the request, queries the corresponding servlet-name in the XML file based on the Action property value, and then queries to the corresponding Java class based on the Servlet-name ( if this is the first time, Tomcat compiles the servlet into a Java class file, so if there are many Servlets, the program will be slow for the first time .

4.Tomcat instantiate the query to the Java class, and note that the class is instantiated only once .

5. Call the Service () method of the Java class object (if the service () method is not overridden, decide whether to execute the Dopost () method or the Doget () method depending on the submission).

6. Through the request object to get the data sent by the client, after processing the data through the response object to write processing results back to the client.

is the servlet thread-safe?

As can be seen from the invocation of the servlet above, Tomcat instantiates the servlet based on the Web. XML configuration file when the client requests the servlet for the first time.

when another client accesses the servlet, the servlet is no longer instantiated, that is, multiple threads are using the instance .

Jsp/servlet container By default is a single-instance multithreading (this is the main cause of thread safety) to handle multiple requests , this design, multi-threaded execution can greatly reduce the resource requirements of the system, improve the system's concurrency and response time.

The servlet itself is stateless, a stateless servlet is absolutely thread-safe, and stateless object design is an effective means of solving thread-safety problems.

Therefore, whether the servlet thread safety is determined by its implementation, if its internal properties or methods will be changed by multiple threads, it is thread insecure, and vice versa, is thread-safe.

The following example comes from the Java Concurrency Programming combat, where thread insecurity exists in race conditions .

public class Unsafecountingfactorizer implements Servlet{private long Count=0;public long GetCount () {return count;} @Overridepublic void Service (ServletRequest req, Servletresponse resp) throws Servletexception, IOException {BigInteger I=extractfromrequest (); Biginteger[] Factors=factor (i); ++count;}}

The increment operation count++ is not an atomic operation , it contains three separate operations: reads the value of count, adds 1,
It then writes the result of the calculation to Coune, which is a "read-modify-write" sequence of operations, and its resulting state depends on the previous state. Errors can occur when the timing of the execution is different.

factors that affect servlet thread safety

Under multithreading, each thread has its own copy of the local variable, so the modification of the local variable affects only its own copy and does not affect other threads, so it is thread-safe.

However, for instance variables, all threads share instance variables because the servlet is in singleton mode in Tomcat. access to shared resources by multiple threads poses a thread insecurity issue .

How do I control thread safety for Servlets?

Avoid using instance variables
Avoid using a non-thread-safe collection
Modifications to an external object (such as a file) in multiple servlets are necessary to locking (Synchronized, or reentrantlock), mutually exclusive access.
Thread-Safe properties: ServletContext, HttpSession are thread-safe, ServletRequest is non-thread safe.

designing a thread-safe servlet

1. Implement the 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. 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. In the current servlet development is basically not see the use of Singlethreadmodel, this way to understand, as far as possible to avoid the use.


2. Synchronizing operations on 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. If you use synchronization in your program to protect the shared data that you want to use, the performance of the system is greatly reduced . 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. So in the actual development should also avoid or minimize the synchronization code in the servlet after synchronization code 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.
Avoiding the use of instance variables in Servlets is the best choice for ensuring that the servlet thread is secure. In the Java memory model, 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 thread security.

Reference:

Servlet working principle parsing servlet Multithreading and servlet thread safety

Multithreading and thread safety for Servlets

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: info-contact@alibabacloud.com 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.