Servlet和ThreadLocal的測試

Servlet和ThreadLocal的測試

很早以前就對Servlet中的變量生命週期不清楚

最近用hibernate又涉及到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

 

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中對象唯一。不同的請求,ObjecthashCode相同。

3 不同的Session共享ThreadLocal,但內部對象不同

另:後來有人提醒我,實際上在web.xml爲同一個servlet配置不同的名字,將會是兩個不同的實例。也就是說,servlet的實例與配置有關。

    


版權聲明:
本文由冰雲完成,作者保留中文版權。
未經許可,不得使用於任何商業用途。
歡迎轉載,但請保持文章及版權聲明完整。
如需聯絡請發郵件:icecloud(AT)sina.com
Blog:
 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章