Analysis of Servlet multithreading Problems

Source: Internet
Author: User

The Servlet multithreading 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. 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.

Improper use of instance variables is the main cause of Servlet multithreading insecurity. The following three solutions are provided for this problem and some reference suggestions are provided for the selection of solutions.

1. Implement SingleThreadModel

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:

 
  1. Public class Concurrent Test extends HttpServlet implements SingleThreadModel {  
  2.      …………  
  3. }  

2. Synchronize operations on shared data

The synchronized keyword ensures that only one thread can access the protected segment at a time. In this paper, the Servlet can guarantee thread security through synchronous block operations. The code after synchronization is as follows:

 
  1. ............
  2.  
  3. Public class Concurrent Test extends HttpServlet {............
  4.  
  5. Username=Request. GetParameter ("username ");
  6.  
  7. Synchronized (this ){
  8.  
  9. Output=Response. GetWriter ();
  10.  
  11. Try {
  12.  
  13. Thread. Sleep (5000 );
  14.  
  15. } Catch (Interrupted Exception e ){}
  16.  
  17. Output. println ("User name:" + Username +"
  18.  
  19. ");
  20.  
  21. }
  22.  
  23. }
  24.  
  25. }

3. Avoid using instance variables

The multi-thread security problem of Servlet in this instance is caused by instance variables. As long as instance variables are not used in any methods 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:

 
  1. ……   
  2.  
  3. Public class Concurrent Test extends HttpServlet                                 
  4.  
  5. {                                                                                  public void service (HttpServletRequest request, HttpServletResponse   
  6.  
  7. Response) throws ServletException,IOException                                                                           {  
  8.  
  9. Print Writer output;   
  10.  
  11. String username;  
  12.  
  13. Response.setContentType ("text/html; charset=gb2312");  
  14.  
  15. ……   
  16.  
  17. }   
  18.  
  19. } 

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 multi-threaded 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, you should also avoid or minimize the synchronization code in the Servlet; In Servlet multithreading, avoiding the use of instance variables is the best choice to ensure the security of Servlet multithreading. We can also know from the Java memory model that the temporary variables in the method allocate space on the stack, and in Servlet multithreading, each thread has its own private stack space, therefore, they do not affect thread security.

  1. What are servlets and common Servlet APIs?
  2. Automatic jump to error page for JSP Servlet instance
  3. 8-point discussion on optimizing JSP Servlet applications
  4. Servlet import event-driven technology in JSP development
  5. What is JSP and comparison with Servlet?

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.