【问题标题】:Is sessionCreated() from a HttpSessionListener automatically synchronized with request.getSession()?来自 HttpSessionListener 的 sessionCreated() 是否自动与 request.getSession() 同步?
【发布时间】:2017-06-22 10:56:51
【问题描述】:

来自HttpSessionListenersessionCreated() 方法是否自动与request.getSession() 调用同步?特别是,我想知道在sessionCreated() 方法中设置会话属性并在servlet 中使用request.getSession().getAttribute("something") 检索属性是否是线程安全的?
例如,拥有

是否是线程安全的
@Override
public void sessionCreated(HttpSessionEvent se) {
  se.getSession().setAttribute("something", new Something());
}

HttpSessionListener,并拥有

Something something = (Something) request.getSession().getAttribute("something");
synchronized(something){
  // do anything with this "something" object
}

HttpServlet?doGet() 方法内部我担心的是,如果这个sessionCreated() 方法没有自动与requested.getSession() 同步,则getAttribute("something") 返回的值可以是null

【问题讨论】:

标签: java multithreading session servlets listener


【解决方案1】:

这两个方法调用在同一个线程中执行,至少在 Tomcat 中是这样。我使用 log4j 打印线程 ID 来检查它。因此,上述方法调用的组合是线程安全的,至少在 Tomcat 中是这样。

【讨论】:

  • 同样适用于 Jetty,顺便说一句
  • Spring 的WebUtils.getSessionMutex() 也假设如果存在由sessionCreated() 初始化的属性,则在其上同步会话访问是安全的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多