Servlet 2.5规范:执行请求线程的多个servlet可以同时主动访问同一会话对象。容器必须确保以线程安全的方式对表示会话属性的内部数据结构进行操作。开发人员负责对属性对象本身进行线程安全访问。这将保护HttpSession对象内部的属性集合免受并发访问,从而消除了应用程序导致该集合损坏的机会。这是安全的:// guaranteed by the spec to be saferequest.getSession().setAttribute("foo", 1);这是不是安全的:HttpSession session = request.getSession();Integer n = (Integer) session.getAttribute("foo");// not thread safe// another thread might be have got stale value between get and setsession.setAttribute("foo", (n == null) ? 1 : n + 1);这不能保证是安全的:// no guarantee that same instance will be returned,// nor that session will lock on "this"HttpSession session = request.getSession();synchronized (session) { Integer n = (Integer) session.getAttribute("foo"); session.setAttribute("foo", (n == null) ? 1 : n + 1);}我已经看到了所提倡的最后一种方法(包括J2EE书籍中的方法),但是Servlet规范不能保证它可以正常工作。您可以使用会话ID创建互斥体,但是必须有更好的方法。