Listener is invoked in the same thread as set|get|removeAttribute()
is invoked.
So, the only race condition may occur when setAttribute()
is invoked in another thread. Given that the average servlet container uses a single thread per HTTP connection (and thus not necessarily per HTTP request when HTTP 1.1 keep-alive
is on), then this race condition may occur when the enduser spawns two completely separate browser instances (not windows/tabs) and copies the session cookie from the one to the other and then simultaneously fires a request from both clients on that session triggering the setAttribute()
method in server.
This is however not an usual real world case. Moreover, the container will all by itself worry about threadsafety of accessing the HttpSession
instance. This is specified in chapter 7.7.1 of Servlet specification (emphasis mine):
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.
So your only concern is the threasafety of the attribute itself. E.g. if it's an ArrayList
, and you worry about its threadsafety, you'd likely want to wrap it in Collections#synchronizedList()
.