The servlet thread safety

Source: Internet
Author: User

What are thread threads?

In Java, thread safety generally manifests itself in two ways:
1, multiple thread access to the same Java instance (read and modify) does not interfere with each other, it is mainly embodied in the keyword synchronized. such as ArrayList and Vector,hashmap and Hashtable (which have synchronized keywords before each method). If you are interator a list object and the other threads remove an element, the problem arises.

2. Each thread has its own field and is not shared across multiple threads. It is mainly embodied in the Java.lang.ThreadLocal class, and there is no Java keyword support, such as static, transient.

A common question, can our servlet declare instance or static fields like JavaBean? What if you can't? What problems will it cause?

The answer is: No. We explain the following examples:


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

public class Simpleservlet extends httpservlet{//A variable that's not thread-safe!       private int counter = 0;              public void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {       DoPost (req, resp);              } public void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {              Resp.getwriter (). println ("<HTML><BODY>");              Resp.getwriter (). println (This + "==>");              Resp.getwriter (). println (Thread.CurrentThread () + ": <br>"); for (int c = 0; c <; C + +) {Resp.getwriter (). println ("Counter =" + Counter + "<                     Br> ");                            try {thread.sleep (long) math.random () * 1000);                     counter++;                   } catch (Interruptedexception exc)  {}} resp.getwriter (). println ("</BODY></HTML>"); }}

We then made three requests to the servlet through an HTML page:

<HTML><BODY><TABLE>    <TR>        <td><iframe src= "./simpleservlet" Name= " Servlet1 "height=" 200% "> </IFRAME></TD>    </TR>    <TR>        <td><iframe Src= "./simpleservlet" Name= "Servlet2" height= "200%" > </IFRAME></TD>    </TR>    <TR>        <td><iframe src= "./simpleservlet" Name= "Servlet3" height= "200%" > </IFRAME></TD>    </TR></TABLE></BODY></HTML>


After you refresh the page several times, the result is:

[Email protected] ==> Thread[http-8081-processor23,5,main]:
Counter = 60
Counter = 61
Counter = 62
Counter = 65
Counter = 68
Counter = 71
Counter = 74
Counter = 77
Counter = 80
Counter = 83

[Email protected] ==> Thread[http-8081-processor22,5,main]:
Counter = 61
Counter = 63
Counter = 66
Counter = 69
Counter = 72
Counter = 75
Counter = 78
Counter = 81
Counter = 84
Counter = 87

[Email protected] ==> Thread[http-8081-processor24,5,main]:
Counter = 61
Counter = 64
Counter = 67
Counter = 70
Counter = 73
Counter = 76
Counter = 79
Counter = 82
Counter = 85
Counter = 88

We will find three points:

The servlet produces only one Servlet object, because the hashcode is the same when the this is output.

Servlets run in different threads (thread pools), such as Http-8081-processor22,http-8081-processor23

Count is shared by these three doget methods and is modified in parallel.

The above results violate the two aspects of thread safety.

So how do we ensure that we run the results as we expect them to? First of all, I want to ensure that the resulting count is executed sequentially.

We refactor the servlet code as follows:

public class Simpleservlet extends httpservlet{  //a variable It's not thread-safe!  private int counter = 0;  Private String Mutex = "";   public void Doget (HttpServletRequest req, HttpServletResponse resp)    throws Servletexception, ioexception{    DoPost (req, resp);  }  public void DoPost (HttpServletRequest req, HttpServletResponse resp)    throws Servletexception, IOException  {    Resp.getwriter (). println ("<HTML><BODY>");    Resp.getwriter (). println (This + ": <br>");    Synchronized (mutex)    {for          (int c = 0; c <; C + +)      {        resp.getwriter (). println ("Counter =" + Count ER + "<BR>");        Try          {          thread.sleep (long) math.random () * +);          counter++;        }        catch (Interruptedexception exc) {}}}    resp.getwriter (). println ("</BODY></HTML>");}  }

Our output results are:


[E mail protected]: 
Counter = 0 
Counter = 1 
Counter = 2 
Counter = 3 
Counter = 4 
Counter = 5 
Counter = 6 
Counter = 7 
Counter = 8 
Counter = 9 

[email protected]: 
Counter = 10 
Counter = 11 
Counter = 12 
Counter = 13 
Counter = 14 
Counter = 15 
Counter = 16 
Counter = 17 
Counter = 18 < Br>counter = 19 

[email protected]: 
Counter = 20 
Counter = 21 
Counter = 22  
Counter = 23 
Counter = 24 
Counter = 25 
Counter = 26 
Counter = 27 
Counter = 28 
Counter = 29 

This fits our requirements and the output is in order, which is what synchronized means.  


The servlet thread safety

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.