Servlet thread security

Source: Internet
Author: User

This article is mainly from zwchen's blog:Http://zwchen.iteye.com/blog/91088

Overview
Before discussing java thread security, let's briefly introduce the Java language.

All languages, such as C ++, C #, and Java, have similarities, especially syntax. But if someone asks you, what is the core of Java? Class Library? Keyword? Syntax? None
Yes.The core of the Java language, that is, Sun is always unwilling to Open Source: Implementation of Java virtual machines(However, sun published its Java Virtual Machine specifications), and BEA's
JRockit, IBM's Jikes, and Sun's Hotspot.

Java has two core points: Java Class Loader and Java memory management. They are embodied in the following classes of Java Class libraries:

Java. lang. ClassLoader (java. lang. Class): The Class we call, including its interfaces and superclasses. How is the import Class loaded by the java Virtual Machine? Why can static fields survive in the servlet container )?

Java. lang. Thread (java. lang. ThreadLocal ):How is garbage collection performed (the garbage collection thread )? How did our program exit?

Java. lang. refelect. Proxy (java. lang. refelect. Method): Why Tomcat,
Container and framework such as Tapestry, Webwork, and Spring can call the class we write through the configuration file? Servlet specification, JSF specification, EJB specification, JDBC
What is the rule? Why are almost all interfaces rather than specific classes?

Servlet thread security

In the Java server side development process, Thread security (Thread
Safe) is a particularly prominent problem. Because containers, such as Servlet and EJB, are generally run in multiple threads. Although we generally do not consider these issues during the development process, we can diagnose them.
(Robust), program optimization (Performance), we must go deep into them.

What is thread security?

Reference Thread-safe
Describes a program portion or routine that can be called from multiple
Programming threads without unwanted interaction between the threads.

In Java, thread security is generally reflected in two aspects:

1. Multiple Threads access the same java instance (read and modify) without interfering with each other. It is mainly reflected in the key word synchronized. For example
ArrayList, Vector, HashMap, and Hashtable (the latter has the synchronized keyword before each method ). If you are
When interator is a List object and other threads remove an element, the problem arises.

2. Each thread has its own field instead of sharing it among multiple threads. It is mainly reflected in the java. lang. ThreadLocal class, and is not supported by Java keywords, such as static and transient.

A general question is, can our Servlet declare instance or static fields like JavaBean? If not? What problems will this cause?

The answer is: no. The following is an example:

First, we write a common Servlet with the instance field count:

Web. xml>

1 <servlet>2     <servlet-name>SimpleServlet</servlet-name>3     <servlet-class>servlet.SimpleServlet</servlet-class>4 </servlet>5 <servlet-mapping>6     <servlet-name>SimpleServlet</servlet-name>7     <url-pattern>/SimpleServlet</url-pattern>8 </servlet-mapping>

SimpleServlet>

 1 public class SimpleServlet extends HttpServlet { 2      private int counter = 0;   3      @Override 4     protected void service(HttpServletRequest request, HttpServletResponse response) 5             throws ServletException, IOException { 6         response.getWriter().println("<HTML><BODY>"); 7         response.getWriter().println(this + " ==> "); 8         response.getWriter().println(Thread.currentThread() + ": <br>");  9         for(int c=0;c<10;c++){10             response.getWriter().println("Counter = " + counter + "<BR>");11             try {12                 Thread.sleep(1000);  13                 counter++;  14             } catch (Exception e) {15                 e.printStackTrace();16             }17         }18         response.getWriter().println("</BODY></HTML>");19     }20 }

Test.html>

1 <HTML>  2     <BODY>  3         <TABLE>  4             <TR>  5                 <TD><IFRAME src="SimpleServlet" name="servlet1" height="200%"> </IFRAME></TD>  6             </TR>  7         </TABLE>  8     </BODY>  9 </HTML>  

Everyone should find that test.html is a little different from zwchen's original blog. It was originally tested in the original zwchen blog, but I believe many people have not come up with the desired results, as the blog commented on the 5th floor: "There is no thread security problem, and the order of numbers is correct", so do I (I use the Firefox browser ). Later, I changed the IE browser for testing and the following problems appeared. Only the content in the first <tr> </tr> was displayed on the page, so my solution was as follows: the content of test.html is shown in the preceding figure. Open the three ie browsers and enter:

A: http: /localhost: 8080/ServletTest/SimpleServlet
B: http: /localhost: 8080/ServletTest/SimpleServlet

 

C: http: // localhost: 8080/ServletTest/SimpleServlet

The test results are as follows:

We will find three points:

1. Servlet is a Singleton object, because we can see that all the printed hashCode values of this pointer in multiple requests are the same.
2. servlet runs in different threads (thread pools), such as http-8080-1, http-8080-2, http-8080-3
And other output values can clearly differentiate different threads that execute different pieces of Servlet logic code.
3. The count variable is shared among different threads, and its value is modified by different threads. The output is no longer sequential. That is to say, other threads tamper with the values of instance variables in the current thread, and access to these objects is not thread-safe.

The above results violate two aspects of thread security.

So, how can we ensure that we run as expected? First, I want to ensure that the generated count is executed sequentially.

The Servlet code is restructured as follows:

 

 1 public class SimpleServlet extends HttpServlet { 2      private int counter = 0;   3      private String mutex = "";  4      @Override 5     protected void service(HttpServletRequest request, HttpServletResponse response) 6             throws ServletException, IOException { 7         response.getWriter().println("<HTML><BODY>"); 8         response.getWriter().println(this + " ==> "); 9         response.getWriter().println(Thread.currentThread() + ": <br>"); 10         synchronized (mutex){11             for(int c=0;c<10;c++){12                 response.getWriter().println("Counter = " + counter + "<BR>");13                 try {14                     Thread.sleep(1000);  15                     counter++;  16                 } catch (Exception e) {17                     e.printStackTrace();18                 }19             }20         }21         response.getWriter().println("</BODY></HTML>");22     }23 }

This meets our requirements, and the output is in order, which formally defines synchronized.

  Additionally, synchronized is a string variable mutex, not a this object. this mainly applies to performance and Scalability. When Synchronized is used on this object, it will cause serious Scalability. All concurrent requests must be queued!

 

 

 

 

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.