Java线程安全系列(1)--Servlet线程安全

概述
在探讨java线程安全前,让我们先简要介绍一下Java语言。

任何语言,如C++,C#,Java,它们都有相通之处,特别是语法,但如果有人问你,Java语言的核心是什么?类库?关键字?语法?似乎都不是。Java语言的核心,也就是Sun始终不愿意开源的东西:Java虚拟机的实现(不过sun公开了其Java虚拟机规范),也就有了BEA的JRockit,IBM的Jikes,Sun的Hotspot。

Java的核心有两点,Java类加载(Java Class Loader)和Java内存管理,它们具体体现在Java类库的以下几个类:

java.lang.ClassLoader(java.lang.Class):我们调用的类,包括其接口和超类,import的类是怎么被Java虚拟机载入的?为什么static的字段在servlet容器里面可以一直生存下去(Spring容器中)?

java.lang.Thread(java.lang.ThreadLocal):垃圾回收是怎么进行的(垃圾回收线程)?我们的程序是怎么退出的?

java.lang.refelect.Proxy(java.lang.refelect.Method):为什么Tomcat、Tapestry、Webwork、Spring等容器和框架可以通过配置文件来调用我们写的类?Servlet规范、JSF规范、EJB规范、JDBC规范究竟是怎么回事?为什么它们几乎都是一些接口,而不是具体类?


Servlet线程安全

在Java的server side开发过程中,线程安全(Thread Safe)是一个尤为突出的问题。因为容器,如Servlet、EJB等一般都是多线程运行的。虽然在开发过程中,我们一般不考虑这些问题,但诊断问题(Robust),程序优化(Performance),我们必须深入它们。

什么是线程安全?


引用
Thread-safe describes a program portion or routine that can be called from multiple programming threads without unwanted interaction between the threads。


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


Java代码
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>");  
       }  


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发出三次请求:

Java代码
<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> 

<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代码重构如下:



Java代码
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>");  
  }  
 


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的含义。

附带说一下,我现在synchronized的是一个字符串变量mutex,不是this对象,这主要是从performance和Scalability考虑。Synchronized用在this对象上,会带来严重的可伸缩性的问题(Scalability),所有的并发请求都要排队!

你可能感兴趣的:(servlet)