首页 | 互联网 | IT动态 | IT培训 | Cisco | Windows | Linux | Java | .Net | Oracle | 软件测试 | C/C++ | 嵌入式开发 | 存储世界 | 服务器
网络设备 | IDC | 安全 | 求职招聘 | 数字网校 | 笔记本电脑 | 北大青鸟 | 技术专题 | 电子书下载 | 教学视频 | 源码下载 | 搜索 | 博客 | 论坛
中国IT实验室Linux频道
中国IT教育
Google
首页 资讯动态 认证考试 新手入门 核心技术 高级技术 J2EE J2ME Java&XML 开源技术 其他技术 RSS订阅 论坛 专题
您现在的位置: 中国IT实验室 >> Java >> J2EE >> Servlet/Jsp >> 正文

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的实例与配置有关。
【责编:admin】

中国IT教育

相关产品和培训
文章评论
 友情推荐链接
 认证培训
 专题推荐

 ·Oracle外键及外键约束修改行为
 ·开源软件测试工具学习专题
 ·JSP Web开发 入门基础到高手进阶教程
 ·JavaFX—是Java桌面的新希望么?
 ·安全至上 .NET开发安全策略
 ·测试用例设计之道-测试用例学习专题
 ·面向Java开发人员的Scala指南
 ·Java设计模式之实例详解
 ·Oracle数据库11g 面向DBA和开发人员的重要新特性
 ·桌面应用软件编程 J2SE技术详解
 今日更新
 社区讨论
 博客论点
 频道精选
 Java 频道导航