2018-01-17 20:05 GMT+03:00 Christopher Schultz <ch...@christopherschultz.net>: > > All, > > I have a use-case related to caching where I need to make sure that an > operation only happens one time with respect to an object in the > session. Basically, I want to build a cache and put it into the > session, but it needs to be thread-safe enough that two threads can't > see the object isn't there, build such an object, and then put it into > the session (thereby overwriting each other). > [...] > > So the question is "what should I use as the monitor?" > > My first thought was that I should use the session object itself: > > Cache myCache = null; > synchronized (session) { > myCache = session.getAttribute("cacheKey"); > if(null == myCache) { > myCache = new Cache(); > session.setAttribute("cacheKey", cache); > } > } > > That would be the best option, since it's the object I actually care > about. However, I believe Tomcat sometimes (always) provides wrapper > objects around servlet-spec-defined objects and I'm wondering if there > are any guarantees about the HttpSession object being consistent > across threads?
I think that the best way is to implement a listener https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionListener.html There is "sessionCreated" event that can be used to create the cache or any kind of a lock object for the cache (e.g. an AtomicReference), See also other HttpSession* listeners in that package, https://docs.oracle.com/javaee/7/api/javax/servlet/http/package-summary.html Best regards, Konstantin Kolinko --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org For additional commands, e-mail: users-h...@tomcat.apache.org