Servlet和ThreadLocal的測試
很早以前就對Servlet中的變量生命週期不清楚
最近用hibernate又涉及到ThreadLocal的使用
做個測試看看到底它們的變量有效範圍
public class TestThreadServlet extends HttpServlet {
private static ThreadLocal thread = new ThreadLocal();
public void doGet( HttpServletRequest request,
throws ServletException, IOException {
String str = "This is the first String." + new Object();
PrintWriter out = response.getWriter();
out.println("<BR>flag : " + flag);
out.println("<BR>sessionid : " + request.getSession().getId());
out.println("<BR>servlet : " + this.toString());
out.println("<BR>thread : " + thread.get());
1 服務器對每個Servlet只創建一個實例。flag不停增加
2 Session範圍內的ThreadLocal中對象唯一。不同的請求,Object的hashCode相同。
3 不同的Session共享ThreadLocal,但內部對象不同
另:後來有人提醒我,實際上在web.xml爲同一個servlet配置不同的名字,將會是兩個不同的實例。也就是說,servlet的實例與配置有關。
版權聲明:
本文由冰雲完成,作者保留中文版權。
未經許可,不得使用於任何商業用途。
歡迎轉載,但請保持文章及版權聲明完整。
如需聯絡請發郵件:icecloud(AT)sina.com
Blog: