Servlet和ThreadLocal的測試

public class TestThreadServlet extends HttpServlet {
  
    private static ThreadLocal thread = new ThreadLocal();
  
    private int   flag = 0;
  
    public void doGet( HttpServletRequest request,HttpServletResponse response)
  
        throws ServletException, IOException {
  
      flag++;
  
      String str = "This is the first String." + new Object();
  
      if (thread.get() == null)
  
        thread.set(str);
  
      PrintWriter out = response.getWriter();
  
      out.println("<p>");
  
      out.println("<BR>flag : " + flag);
  
      out.println("<BR>sessionid : " + request.getSession().getId());
  
      out.println("<BR>servlet : " + this.toString());
  
      out.println("<BR>thread : " + thread.get());
  
      out.println("</p>");
  
    }
  
  }
  
  執行結果:
  
  Session 1:
  
  flag : 2
  sessionid : amGeaiVwKvL9
  servlet : test.other.TestThreadServlet@5f2db0
  thread : This is the first String.Java.lang.Object@1ad6b4b
  
  Session 1:
  
  flag : 3
  sessionid : aR3GkcUQoXT-
  servlet : test.other.TestThreadServlet@5f2db0
  thread : This is the first String.java.lang.Object@6214f5
  
  由執行結果能夠看出
  
  1 服務器對每一個Servlet只建立一個實例。flag不停增長
  
  2 Session範圍內的ThreadLocal中對象惟一。不一樣的請求,Object的hashCode相同。
  
  3 不一樣的Session共享ThreadLocal,但內部對象不一樣
  
  另:後來有人提醒我,實際上在web. XML爲同一個servlet配置不一樣的名字,將會是兩個不一樣的實例。也就是說,servlet的實例與配置有關。
相關文章
相關標籤/搜索