I'm trying to get my head around the ThreadLocal pattern (although I can't find it anymore in the Wiki) and I would really appreciate your help. I did have a read through the forum but I couldn't really find an answer.
Lets see the standard
getSession() method of the pattern
Code:
Session s = (Session) threadSession.get();
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
return s;
Isn't it possible that two threads would get two different Session objects since the block isn't synchronized?
Seeing as one thread comes around, finds Session to be
null tries to acquire a new one, at that time a second one comes around and since the first one hasn't really assigned the Session to the Threadlocal, gets
null as well.
So the two threads end up with 2 sessions out of which only 1 of them gets closed when calling the
closeSession().
Code:
Session s = (Session) threadSession.get();
threadSession.set(null);
if (s != null && s.isOpen()) {
log.debug("Closing Session of this thread.");
s.close();
}
Thanks in advance.