Search code examples
javamysqlhibernatec3p0

closed connections in c3p0


I´m starting with Hibernate. Since I read that I need to configure the pool connection I start using C3P0

everything is fine, but when I reach the maximum connections the application freezes, I have to close the application and start it again.

this is my C3P0 part in hibernate.cfg.xml

<property name="hibernate.c3p0.min_size">1</property> 
<property name="hibernate.c3p0.max_size">15</property>
<property name="hibernate.c3p0.timeout">3000</property>  
<property name="hibernate.c3p0.max_statements">20</property>
<property name="hibernate.c3p0.idle_test_period">300</property>

in my function when I save the object I close the session.

   

 public void Save item(Item item)throws Exception{    
            try{          
            SessionFactory sf= NewHibernateUtil.getSessionFactory();
            Session session;
            session = sf.openSession();
            Transaction tx= session.beginTransaction(); 
            session.save(item); 
            tx.commit();
            session.close();          
            }
            catch(Exception ex){
                throw new Exception(ex);
            }
        }

if I check the connections in MySql I see that all the connections are sleep, but the application freezes.

what am I missing here?


Solution

  • You are not reliably close()ing Connections (wrapped within Sessions), so they leak. Consider what happens when an Exception occurs.

    Either use Java 7+ try-with-resources, if Session supports that, or use the old robust cleanup idiom, see the Appendix to my answer here.

    If you fix this and are still experiencing a Connection leak, c3p0 has configuration parameters to help you track down the leak.