Servlet is single-instance, so thread security is required and how to implement thread security

Source: Internet
Author: User

Compared with ASP and PHP, Servlet/JSP has a high execution efficiency due to its multi-threaded operation. Servlet/JSP is executed in multi-thread mode by default. Therefore, you must carefully consider the security of multiple threads when writing code. However, many developers have not noticed the multi-thread security issue when writing Servlet/JSP programs, which often causes no problems when a few users access the program, when the number of concurrent users reaches a certain value, some unknown problems often occur. Servlet multithreading mechanism the Servlet architecture is built on the Java multithreading mechanism, and its lifecycle is the responsibility of Web containers. When the client requests a Servlet for the first time, the Servlet container will instantiate the Servlet class according to the web. xml configuration file. When a new client requests the Servlet, the Servlet class is generally not instantiated, that is, multiple threads are using this instance. Servlet containers automatically Use thread pools and other technologies to support system running, as shown in figure 1. Figure 1 Servlet thread pool: When two or more threads access the same Servlet at the same time, multiple threads may access the same resource at the same time, and the data may become inconsistent. Therefore, if you do not pay attention to thread security issues when using Servlet to build Web applications, the Servlet program will be hard to find errors. Servlet thread security problems are mainly caused by improper use of instance variables. Here is a realistic example. Import javax. servlet. *; Import javax. servlet. http. *; Import java. io. *; Public class Concurrent Test extends HttpServlet {PrintWriter output; Public void service (HttpServletRequest request, www.2cto. comHttpServletResponse response) throws ServletException, IOException {String username; Response. setContentType ("text/html; charset = gb2312"); Username = request. getParameter ("username"); Output = re Else se. getWriter (); Try {Thread. sleep (5000); // to highlight concurrency issues, set a latency} Catch (Interrupted Exception e) {} output. println ("Username:" + Username + "<BR>") ;}} this Servlet defines an instance variable output, which is assigned to the user output in the service method. When a user accesses the Servlet, the program runs normally, but when multiple users access the Servlet concurrently, the information of other users may be displayed on the browsers of other users. This is a serious problem. To highlight concurrency issues and facilitate testing and observation, we performed a delayed operation when returning user information. Assume that. the Servlet is registered in the xml configuration file. Currently, two users a and B can access the Servlet at the same time (two ie browsers can be started or accessed simultaneously on both machines ), in the browser, enter a: http: // localhost: 8080/servlet/ConcurrentTest? Username = a B: http: // localhost: 8080/servlet/ConcurrentTest? Username = B if user B is a little slower than user a's carriage return time, the output shown in Figure 2 is displayed. Figure 2 shows the browser output of user a and user B, the Web server starts two threads to process requests from user a and user B respectively, but a blank screen is displayed on user a's browser, user a's information is displayed on user B's browser. The Servlet has thread insecurity issues. Next we will start with analyzing the memory model of the instance and observe the output value of the instance variable at different times to analyze the cause of the Servlet thread being unsafe. The Java Memory Model JMM (Java Memory Model) JMM defines the relationship between threads and Memory. According to the JMM design, the system has a Main Memory (Main Memory). All instance variables in Java are stored in the Main Memory, and all threads are shared. Each thread has its own Working Memory. The Working Memory is composed of two parts: the cache and the stack. The cache stores copies of variables in the main Memory, the cache may not always synchronize the primary memory, that is, the modifications to the variables in the cache may not be immediately written to the primary memory; the stack stores the local variables of the thread, threads cannot directly access the variables in the stack. Based on JMM, We can abstract the memory model of the Servlet instance discussed in this paper into the model shown in figure 3. Figure 3 The JMM model of the Servlet instance is based on the memory model shown in Figure 3 to analyze the concurrent execution of user a and B threads (for short, thread a and thread B, variable changes and thread execution in the Servlet instance, as shown in figure 4. Scheduling time a thread B thread T1 access Servlet page T2 access Servlet page T3 output = a output username = a Sleep 5000 milliseconds, let out the output of CPU T4 output = B (write back to main memory) username = B sleep for 5000 milliseconds, so that CPUT5 outputs the username value of thread a in user B's browser, and thread a terminates. T6 outputs the username value of line B on user B's browser, and line B ends. Figure 4 the thread scheduling of the Servlet instance can be clearly seen in figure 4. Because the modification of the B thread to the instance variable output overwrites the modification of the thread to the instance variable output, as a result, user a's information is displayed on user B's browser. If, when thread a executes the output statement, the changes made by thread B to the output are not refreshed to the primary storage, the output result shown in Figure 2 is not displayed. Therefore, this is just an accidental phenomenon, but this increases the potential risks of the program. Through the above analysis, the Servlet designed for thread security knows that incorrect use of instance variables is the main cause of Servlet thread insecurity. The following three solutions are provided for this problem and some reference suggestions are provided for the selection of solutions. 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, no two threads will be executed simultaneously in the service method of this Servlet. Of course, there is no thread security problem. In this method, you only need to change the class header definition of the previous Concurrent Test class to: Public class Concurrent Test extends HttpServlet implements SingleThreadModel {............} 2. synchronous operations on shared data use the synchronized keyword to ensure that only one thread can access protected segments at a time, in this thesis, Servlet can guarantee thread security by synchronizing block operations. The code after synchronization is as follows :............ Public class Concurrent Test extends HttpServlet {............ Username = request. getParameter ("username"); Synchronized (this) {Output = response. getWriter (); Try {Thread. sleep (5000);} Catch (Interrupted Exception e) {} output. println ("Username:" + Username + "<BR>") ;}}3. Avoid using instance variables. thread security issues in this instance are caused by instance variables, as long as no instance variable is used in any method in the Servlet, the Servlet is thread-safe. Modify the Servlet code above and change the instance variable to a local variable to implement the same function. The Code is as follows :...... Public class Concurrent Test extends HttpServlet {public void service (HttpServletRequest request, HttpServletResponse Response) throws ServletException, IOException {Print Writer output; String username; Response. setContentType ("text/html; charset = gb2312 ");......} The above three methods can be tested to show that all of them can be used to design thread-safe Servlet programs. 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 large amount of system overhead. SingleThreadModel is no longer recommended in Servlet2.4. If synchronization is used in a program to protect the shared data to be used, the system performance will be greatly reduced. This is because the synchronized code block can only be executed by one thread at a time, reducing the throughput for simultaneously processing customer requests and blocking many customers. In addition, to ensure data consistency between the main memory and the working memory of the thread, the cache should be refreshed frequently, which will greatly affect the system performance. Therefore, in actual development, we should also avoid or minimize the synchronization code in the Servlet; In Serlet, avoiding using instance variables is the best choice to ensure Servlet thread security. We can also know from the Java memory model that the temporary variables in the method allocate space on the stack, and each thread has its own private stack space, so they do not affect thread security. Compared with ASP and PHP, Servlet/JSP has a high execution efficiency due to its multi-threaded operation. Servlet/JSP is executed in multi-thread mode by default. Therefore, you must carefully consider the security of multiple threads when writing code. However, many developers have not noticed the multi-thread security issue when writing Servlet/JSP programs, which often causes no problems when a few users access the program, when the number of concurrent users reaches a certain value, some unknown problems often occur. Servlet multithreading mechanism the Servlet architecture is built on the Java multithreading mechanism, and its lifecycle is the responsibility of Web containers. When the client requests a Servlet for the first time, the Servlet container will instantiate the Servlet class according to the web. xml configuration file. When a new client requests the Servlet, the Servlet class is generally not instantiated, that is, multiple threads are using this instance. Servlet containers automatically Use thread pools and other technologies to support system running, as shown in figure 1. Figure 1 Servlet thread pool: When two or more threads access the same Servlet at the same time, multiple threads may access the same resource at the same time, and the data may become inconsistent. Therefore, if you do not pay attention to thread security issues when using Servlet to build Web applications, the Servlet program will be hard to find errors. Servlet thread security problems are mainly caused by improper use of instance variables. Here is a realistic example. Import javax. servlet. *; Import javax. servlet. http. *; Import java. io. *; Public class Concurrent Test extends HttpServlet {PrintWriter output; Public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String username; Response. setContentType ("text/html; charset = gb2312"); Username = request. getParameter ("username"); Output = response. getWri Ter (); Try {Thread. sleep (5000); // to highlight concurrency issues, set a latency} Catch (Interrupted Exception e) {} output. println ("Username:" + Username + "<BR>") ;}} this Servlet defines an instance variable output, which is assigned to the user output in the service method. When a user accesses the Servlet, the program runs normally, but when multiple users access the Servlet concurrently, the information of other users may be displayed on the browsers of other users. This is a serious problem. To highlight concurrency issues and facilitate testing and observation, we performed a delayed operation when returning user information. Assume that. the Servlet is registered in the xml configuration file. Currently, two users a and B can access the Servlet at the same time (two ie browsers can be started or accessed simultaneously on both machines ), in the browser, enter a: http: // localhost: 8080/servlet/ConcurrentTest? Username = a B: http: // localhost: 8080/servlet/ConcurrentTest? Username = B if user B is a little slower than user a's carriage return time, the output shown in Figure 2 is displayed. Figure 2 shows the browser output of user a and user B, the Web server starts two threads to process requests from user a and user B respectively, but a blank screen is displayed on user a's browser, user a's information is displayed on user B's browser. The Servlet has thread insecurity issues. Next we will start with analyzing the memory model of the instance and observe the output value of the instance variable at different times to analyze the cause of the Servlet thread being unsafe. The Java Memory Model JMM (Java Memory Model) JMM defines the relationship between threads and Memory. According to the JMM design, the system has a Main Memory (Main Memory). All instance variables in Java are stored in the Main Memory, and all threads are shared. Each thread has its own Working Memory. The Working Memory is composed of two parts: the cache and the stack. The cache stores copies of variables in the main Memory, the cache may not always synchronize the primary memory, that is, the modifications to the variables in the cache may not be immediately written to the primary memory; the stack stores the local variables of the thread, threads cannot directly access the variables in the stack. Based on JMM, We can abstract the memory model of the Servlet instance discussed in this paper into the model shown in figure 3. Figure 3 The JMM model of the Servlet instance is based on the memory model shown in Figure 3 to analyze the concurrent execution of user a and B threads (for short, thread a and thread B, variable changes and thread execution in the Servlet instance, as shown in figure 4. Scheduling time a thread B thread T1 access Servlet page T2 access Servlet page T3 output = a output username = a Sleep 5000 milliseconds, let out the output of CPU T4 output = B (write back to main memory) username = B sleep for 5000 milliseconds, so that CPUT5 outputs the username value of thread a in user B's browser, and thread a terminates. T6 outputs the username value of line B on user B's browser, and line B ends. Figure 4 the thread scheduling of the Servlet instance can be clearly seen in figure 4. Because the modification of the B thread to the instance variable output overwrites the modification of the thread to the instance variable output, as a result, user a's information is displayed on user B's browser. If, when thread a executes the output statement, the changes made by thread B to the output are not refreshed to the primary storage, the output result shown in Figure 2 is not displayed. Therefore, this is just an accidental phenomenon, but this increases the potential risks of the program. Through the above analysis, the Servlet designed for thread security knows that incorrect use of instance variables is the main cause of Servlet thread insecurity. The following three solutions are provided for this problem and some reference suggestions are provided for the selection of solutions. 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, no two threads will be executed simultaneously in the service method of this Servlet. Of course, there is no thread security problem. In this method, you only need to change the class header definition of the previous Concurrent Test class to: Public class Concurrent Test extends HttpServlet implements SingleThreadModel {............} 2. synchronous operations on shared data use the synchronized keyword to ensure that only one thread can access protected segments at a time, in this thesis, Servlet can guarantee thread security by synchronizing block operations. The code after synchronization is as follows :............ Public class Concurrent Test extends HttpServlet {............ Username = request. getParameter ("username"); Synchronized (this) {Output = response. getWriter (); Try {Thread. sleep (5000);} Catch (Interrupted Exception e) {} output. println ("Username:" + Username + "<BR>") ;}}3. Avoid using instance variables. thread security issues in this instance are caused by instance variables, as long as no instance variable is used in any method in the Servlet, the Servlet is thread-safe. Modify the Servlet code above and change the instance variable to a local variable to implement the same function. The Code is as follows :...... Public class Concurrent Test extends HttpServlet {public void service (HttpServletRequest request, HttpServletResponse Response) throws ServletException, IOException {Print Writer output; String username; Response. setContentType ("text/html; charset = gb2312 ");......} The above three methods can be tested to show that all of them can be used to design thread-safe Servlet programs. 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 large amount of system overhead. SingleThreadModel is no longer recommended in Servlet2.4. If synchronization is used in a program to protect the shared data to be used, the system performance will be greatly reduced. This is because the synchronized code block can only be executed by one thread at a time, reducing the throughput for simultaneously processing customer requests and blocking many customers. In addition, to ensure data consistency between the main memory and the working memory of the thread, the cache should be refreshed frequently, which will greatly affect the system performance. Therefore, in actual development, we should also avoid or minimize the synchronization code in the Servlet; In Serlet, avoiding using instance variables is the best choice to ensure Servlet thread security. We can also know from the Java memory model that the temporary variables in the method allocate space on the stack, and each thread has its own private stack space, so they do not affect thread security. For classes with thread insecurity, how to avoid thread security issues: 1. Use synchronized synchronization. The disadvantage is that there is a blockage problem. You can use the read lock and write lock. 2. Use ThreadLocal (actually a HashMap), so that different threads maintain their own objects without interfering with each other.

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.