In-depth exploration of Servlet 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.

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.

In this way, 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 issues

Servlet thread security problems are mainly caused by improper use of instance variables. Here is a realistic example.

 
  1. Import javax. servlet .*;
  2. Import javax. servlet. http .*;
  3. Import java. io .*;
  4. PublicClassConcurrent TestExtendsHttpServlet {PrintWriter output;
  5. PublicVoidService (HttpServletRequest request,
  6. HttpServletResponse response)ThrowsServletException, IOException {String username;
  7. Response. setContentType ("Text/html; charset = gb2312");
  8. Username = request. getParameter ("Username");
  9. Output = response. getWriter ();
  10. Try {Thread. sleep (5000);// Set a latency here to highlight concurrency issues 
  11. } Catch (Interrupted Exception e ){}
  12. Output. println ("User name :"+ Username +"<BR>");
  13. }
  14. }

The 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 to start two ie browsers or access the Servlet on both machines at the same time ), enter:

A: http: // localhost: 8080/servlet/ConcurrentTest? Username =

B: http: // localhost: 8080/servlet/ConcurrentTest? Username = B

If user B is a little slower than user a's carriage return time, output 2 is displayed:

As shown in figure 2, 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.

Java Memory Model JMMJava Memory Model) JMM is mainly used to specify 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.

The following uses the memory model shown in Figure 3 to analyze the concurrent execution of threads a and B, variables and thread execution in the Servlet instance are shown in the following table.

Scheduling time Thread Line B
T1 Access the Servlet page  
T2   Access the Servlet page
T3 Output = username of output = a sleep for 5000 milliseconds, giving way to the CPU  
T4   Output = B's output is written back to the primary storage) username = B sleep for 5000 milliseconds, giving the CPU
T5 Output the username value of thread a in user B's browser, and thread a terminates.
T6   Output the username value of line B in user B's browser, and line B is terminated.

From the preceding table, we can clearly see that the modification of thread B to instance variable output overwrites that of thread a to 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.

  1. Analysis on the working principle of JSP + JavaBean + Servlet Structure
  2. Differences between Servlet page Jump implementation methods
  3. Analysis of Servlet multithreading Problems
  4. Security multithreading in Servlet containers
  5. At the beginning of JSP Servlet Development

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.