I deployed webservices with tomcat6/axis2 using hibernate. I used a standard HibernateUtil class to provide the SessionFactory. Nevertheless, I had a memory leak due to the ThreadLocal within .
Then I rewrote another one to be worked in multithreading environment.
Do you think it is a good way to proceed ?
package com.cambyze.myLibrary.hibernate;
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HibernateUtil {
public static final Log log = LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory = buildSessionFactory();
private static Session session; // current session to be used for every // clients
private static int nbClients = 0; // Number of clients using the current // session
private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }
public static SessionFactory getCurrentSessionFactory() { if (session == null) { log.debug("getSessionFactory Factory open ?" + !sessionFactory.isClosed());
} else { log.debug("getSessionFactory Factory open ?" + !sessionFactory.isClosed() + "Session open ? : " + sessionFactory.getCurrentSession().isOpen()); }
return sessionFactory; }
public static synchronized void OpenSession() { if (nbClients == 0) { log.debug("Open session for the 1st client / Factory open ?" + !sessionFactory.isClosed()); session = sessionFactory.openSession(); } nbClients++; log.debug("Nb clients : " + nbClients); }
public static Session getCurrentSession() { if (session == null) { log.debug("SEVERE no instance of session / Factory open ?" + !sessionFactory.isClosed()); session = sessionFactory.openSession();
} else { log.debug("getSessionFactory Factory open ?" + !sessionFactory.isClosed() + "Session open ? : " + session.isOpen()); } return session; }
public static synchronized void CloseSession() { nbClients--; if (session == null) { log.debug("Session already closed"); } else session.close(); session = null; }
}
|