---
title: "Servlet和ThreadLocal的测试"
author: "冰云"
date: "2004-05-25T10:30:00Z"
tags: []
slug: "servlet-threadlocal"
draft: false
lastmod: "2004-05-25T10:30:00Z"
id: 34959
url: "https://icecloud.iteye.com/blog/34959"
---

### 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(**"&lt;p&gt;"**);  
\
out.println(**"&lt;BR&gt;flag : "** + flag);  
\
out.println(**"&lt;BR&gt;sessionid : "** + request.getSession().getId());  
\
out.println(**"&lt;BR&gt;servlet : "** + **this**.toString());  
\
out.println(**"&lt;BR&gt;thread : "** + thread.get());  
\
out.println(**"&lt;/p&gt;"**);  
\
}  
\
}  
\
\
\
\
\
执行结果：  
\
\
\
\
\
**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的实例与配置有关。  
\
\
\
**版权声明：**  
本文由冰云完成，作者保留中文版权。  
未经许可，不得使用于任何商业用途。  
欢迎转载，但请保持文章及版权声明完整。  
如需联络请发邮件：icecloud(AT)sina.com  
Blog：http://icecloud.51.net]()  
 

[]()