Servlet和ThreadLocal的测试

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

public class TestThreadServlet extends HttpServlet {

private static ThreadLocalthread = 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("<BRflag : " + flag);

out.println("<BRsessionid : " + request.getSession().getId());

out.println("<BRservlet : " + this.toString());

out.println("<BRthread : " + 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的实例与配置有关。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航