开发者

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:

How to release multiple org.hibernate.impl.SessionFactoryImpl

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 = D开发者_如何学PythonaoSF.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?


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.


You're creating and initializing a new SessionFactory every time you need a session. Your getSessionFactory method should check if you already have one instead of always creating a new one.


First of all you should close connection and session in finally statement. Maybe there are some exceptions and session is not closed? Second, hibernate had bugs connected with no closing sessions. Look at this thread: OutofMemory: SessionImpl cached even after close and flush?.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜