考虑算法:
- session 中添加了一个新属性
session.setAttribute("myObject", new Object);
- HttpSessionAttributeListener#attributeAdded被调用
session.setAttribute
之后的代码
HttpSessionAttributeListener#attributeAdded
是否会阻止 session.setAttribute
或监听器代码调用异步?
最佳答案
监听器在调用 set|get|removeAttribute()
的同一线程中调用。
因此,当在另一个线程中调用 setAttribute()
时,可能会出现唯一的竞争条件。鉴于平均 servlet 容器使用 single thread per HTTP connection (因此,当 HTTP 1.1 keep-alive
打开时,不一定是每个 HTTP 请求),那么当最终用户生成两个完全独立的浏览器实例(不是窗口/选项卡)并复制 session 时,可能会发生这种竞争情况cookie 从一个到另一个,然后同时在该 session 上触发来自两个客户端的请求,从而触发服务器中的 setAttribute()
方法。
然而,这并不是现实世界中常见的情况。此外,容器本身会担心访问 HttpSession 实例的线程安全性。这在 Servlet specification 的第 7.7.1 章中指定。 (强调我的):
7.7.1 Threading Issues
Multiple servlets executing request threads may have active access to the same session object at the same time. The container must ensure that manipulation of internal data structures representing the session attributes is performed in a thread safe manner. The Developer has the responsibility for thread safe access to the attribute objects themselves. This will protect the attribute collection inside the
HttpSession
object from concurrent access, eliminating the opportunity for an application to cause that collection to become corrupted.
所以你唯一关心的是属性本身的威胁。例如。如果它是一个 ArrayList,并且您担心它的线程安全性,您可能希望将其包装在 Collections#synchronizedList()
中.
关于java - HttpSessionAttributeListener 是否异步处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33274965/