3

Is sessionCreated() method from a HttpSessionListener automatically synchronized with request.getSession() call? In particular, I would like to know if it is thread safe to set a session attribute in the sessionCreated() method and retrieve the attribute with request.getSession().getAttribute("something") in a servlet?
For example, is it thread-safe to have

@Override
public void sessionCreated(HttpSessionEvent se) {
  se.getSession().setAttribute("something", new Something());
}

in a HttpSessionListener, and have

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

inside of a doGet() method of a HttpServlet? The point of my concern is that if this sessionCreated() method is not automatically synchronized with requested.getSession() the value returned by getAttribute("something") can be null.

Alex T
  • 31
  • 3
  • related questions: https://stackoverflow.com/questions/53158685/is-httpsessionlistener-sessioncreated-guaranteed-to-complete-before-any-other and https://stackoverflow.com/questions/9802165/is-synchronization-within-an-httpsession-feasible – morgwai Nov 08 '21 at 10:47

1 Answers1

0

These two method calls are executed in the same thread, at least in Tomcat. I checked it with printing thread IDs using log4j. Therefore, the combination of the method calls, described above, is thread-safe, at least in Tomcat.

Alex T
  • 31
  • 3