Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release multiple org.hibernate.impl.SessionFactoryImpl

Continue solving this problem, i've found couple of 'org.hibernate.impl.SessionFactoryImpl' memory leaks using MAT:

54 instances of "org.hibernate.impl.SessionFactoryImpl", loaded by "org.apache.catalina.loader.WebappClassLoader @ 0xbb00fb0" occupy 33 962 536 (64,40%) bytes. 

Biggest instances:

org.hibernate.impl.SessionFactoryImpl @ 0x3f026c0 - 652 664 (1,24%) bytes. 
org.hibernate.impl.SessionFactoryImpl @ 0x49018f8 - 652 664 (1,24%) bytes. 
org.hibernate.impl.SessionFactoryImpl @ 0x7b0e2b8 - 652 664 (1,24%) bytes. 
org.hibernate.impl.SessionFactoryImpl @ 0x7d65e60 - 652 664 (1,24%) bytes.
...

Detail: enter image description here

DaoSF.java

public final class DaoSF implements Serializable
{
  private static final long serialVersionUID = 1L;
  private static SessionFactory sessionFactory;
  private static Session hibSession;

  private synchronized static void initSessionFactory() {
    Configuration config = new Configuration();
    config.configure("hibernate.cfg.xml"); 
    sessionFactory = config.buildSessionFactory();
    hibSession = sessionFactory.getCurrentSession();
  }

  public static SessionFactory getSessionFactory() {
    initSessionFactory();
    return sessionFactory;
  }

  public static Session getSession(){ 
    return hibSession;
  }
}

part of DaoCrud.java:

  public void save(Object dataItem) throws Exception 
  { 
    session = DaoSF.getSessionFactory().openSession();

    Transaction tx = session.beginTransaction();  
    session.save(dataItem);  
    session.flush();
    tx.commit();  

    if (session != null) session.close();
  }

part of Bean.java

 public void save() {
   try {
     mydao.save(item);
   }
   catch (Exception e) {...}
   }  
 }

What I'm doing wrong? How to correctly use session factory? Could you help me?

like image 250
gaffcz Avatar asked Apr 20 '26 01:04

gaffcz


1 Answers

It will be better if you can create a Class HibernateSession which will handle open, close, and rollback transaction.

You should put session.close() in finally statement and then assign null to session and transaction just to make sure that they will be garbage collected.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!