Servlet之线程安全

什么是线程安全线程?

在Java里,线程安全一般体现在两个方面: 
1、多个thread对同一个java实例的访问(read和modify)不会相互干扰,它主要体现在关键字synchronized。如ArrayList和Vector,HashMap和Hashtable(后者每个方法前都有synchronized关键字)。如果你在interator一个List对象时,其它线程remove一个element,问题就出现了。 

2、每个线程都有自己的字段,而不会在多个线程之间共享。它主要体现在java.lang.ThreadLocal类,而没有Java关键字支持,如像static、transient那样。 

一个普遍的疑问,我们的Servlet中能够像JavaBean那样declare instance或static字段吗?如果不可以?会引发什么问题? 

答案是:不可以。我们下面以实例讲解: 


首先,我们写一个普通的Servlet,里面有instance字段count:

public class SimpleServlet extends HttpServlet

{
       // A variable that is 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 < 10; c++)
              {
                     resp.getWriter().println("Counter = " + counter + "<BR>");
                     try
                     {
                            Thread.sleep((long) Math.random() * 1000);
                            counter++;
                     }
                     catch (InterruptedException exc)
                     {
                     }
              }
              resp.getWriter().println("</BODY></HTML>");
       }
}

然后,我们通过一个html页面向该servlet发出三次请求: 

<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>


刷新页面几次后,产生的结果为:

com.zwchen.servlet.SimpleServlet@11e1bbf ==> 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 

com.zwchen.servlet.SimpleServlet@11e1bbf ==> 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 

com.zwchen.servlet.SimpleServlet@11e1bbf ==> 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 

我们会发现三点: 

servlet只产生了一个Servlet对象,因为输出this时,其hashcode都一样, 

servlet在不同的线程(线程池)中运行,如http-8081-Processor22,http-8081-Processor23 

Count被这三个doGet方法共享,并且并行修改。 

上面的结果,违反了线程安全的两个方面。 

那么,我们怎样保证按照我们期望的结果运行呢?首先,我想保证产生的count都是顺序执行的。 

我们将Servlet代码重构如下: 

public class SimpleServlet extends HttpServlet

{

  //A variable that is 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 < 10; c++)
      {
        resp.getWriter().println("Counter = " + counter + "<BR>");
        try
          {

          Thread.sleep((long) Math.random() * 1000);
          counter++;
        }
        catch (InterruptedException exc) { }
      }
    }
    resp.getWriter().println("</BODY></HTML>");
  }

}

我们的输出结果为: 


com.zwchen.servlet.SimpleServlet@109da93: 
Counter = 0 
Counter = 1 
Counter = 2 
Counter = 3 
Counter = 4 
Counter = 5 
Counter = 6 
Counter = 7 
Counter = 8 
Counter = 9 

com.zwchen.servlet.SimpleServlet@109da93: 
Counter = 10 
Counter = 11 
Counter = 12 
Counter = 13 
Counter = 14 
Counter = 15 
Counter = 16 
Counter = 17 
Counter = 18 
Counter = 19 

com.zwchen.servlet.SimpleServlet@109da93: 
Counter = 20 
Counter = 21 
Counter = 22 
Counter = 23 
Counter = 24 
Counter = 25 
Counter = 26 
Counter = 27 
Counter = 28 
Counter = 29 

这符合了我们的要求,输出都是按顺序的,这正是synchronized的含义。 


你可能感兴趣的:(java,servlet,线程安全)