I would like to ask you for your opinion on best practice how to close sessions when using ThreadLocal pattern in clustered environment.
I have two node cluster(jboss). Node1, Node2 each runing Service1:
Service1 provide method like:
Code:
class Service1 {
public methodCalledOnCluster() {
Sesson s = ThreadLocalHibernateSession.getSession();
o = s.load(Some.class, id)'
...do something...
s.saveOrUpdate(o);
s.close(); // [1] Here is cause of problem
}
}
There is another service Service2 runing on Node1 that calls Service1.methodCalledOnCluster() for each Node.
Code:
class Service2 {
public someBussinesMethod() {
Sesson s = ThreadLocalHibernateSession.getSession();
... manipulate some objects loaded from session...
Call methodCalledOnCluster() //info
... manipulate some loaded loaded from session...//[2]Exception
s.close();
}
}
So what happens? When someBussinesMethod calls methodCalledOnCluster() on Node1 is this method called localy in same thread. On node2 is this method called of course in new thread. As result
calling s.close() (see line [1]) will close session and I have problems manipulating lazy colection (see line [2]).
I cannot simply remove s.close() in place [1] because it will produce stale unclosed sessions on Node2.
I have read all related patterns and forum articles but I am not sure how to fix it. Major change of architecture (eg. use Command pattern) is not possible. Have you got any idea how can I solve this?
Cheers
David