Is access to ServletContext and Session attributes thread safe?
Created May 7, 2012
For example, is the following code thread safe?
public void setServletAttr( String theAttr, String theValue ) {
getServletContext().setAttribute( theAttr, theValue );
}
public void setSessionAttr( HttpServletRequest request, String theAttr, String theValue ) {
request.getSession().setAttribute( theAttr, theValue );
}
Thanks. This has been killing me!
----------------------------------------
Since both ServletContext
and HttpSession
are interfaces, how thread-safe they are depends on their implementations.
That said, I wouldn't think that you would have to worry about this issue much. Since HttpSession
objects are unique to each user, you probably won't be accessing any of these with more than one thread at the same time. As for ServletContext
objects - nearly all the methods are read methods. And since the only objects you will be putting in the ServletContext
are application wide in scope, you will probably want to put these in at the apps startup anyway and read them from that point on.
BTW, it appears that both of these implementation in Tomcat 3.2.2 have no sychronization.
Hope this helps.