Suppose I have the following:
public class DAOFactory {
@Inject private final SessionFactory factory;
private final ThreadLocal<Session> session = new ThreadLocal<>();
// In a nutshell: create an AbstractDAO associated with the session object held by the ThreadLocal above
public <T> AbstractDAO<T> createObject(Class<T> objectClass) { ... }
}
The problem that I have is that these sessions need to be closed, and only the thread creating the DAO from createObject()
can do that. Clearly, AbstractDAO
cannot have a close routine, since the same Session
can be associated with multiple AbstractDAO
objects, so DAOFactory
has to shoulder the burden of closing sessions. Still, there is a risk of dangling Session
s: if the thread creating the AbstractDAO
no longer exists, how can the associated Session
be closed?
One approach I have is to have a cleanup method as follows:
public class DAOFactory {
// createObject() uses Thread.getCurrentThread.getId() and sessionMap.computeIfAbsent()
private final ConcurrentMap<Long, Session> sessionMap = new ConcurrentHashMap<>();
public void cleanup() {
for (Session session : sessionMap.values()) {
session.close();
}
sessionMap.clear();
}
}
The question is "how safe is this approach", "is this a good idea", and "should this be done"? If not, what's a good alternative?
Note that DAOFactory
is largely created with some kind of testing situation in mind: one thread starts a test run and creates a DAOFactory
, and it may spawn other threads that uses it. The thread creating DAOFactory
will always outlast any threads that it spawns, and will always be the one calling cleanup()
at the end of a test.
Manual Session management is not a good idea. Hibernate already offers a SPI, so that you don't have to do it yourself.
I suggest you start using Spring transaction management, which also offers automatic session management as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.