Hibernate 4.3.5 main method never terminates JVM not finish

Problem

When using Hibernate 4.3.5 in my java application standalone main method finish but JVM never stop or terminate. I run in debug mode and see below thread:

Daemon Thread [Abandoned connection cleanup thread] (Running)


This my main method:

public static void main(String[] args) {
		Session session = null;
		Transaction txn = null;
		try {
			session = HibernateUtil.openSession();
			User user = new User();
			user.setCrtDate(new Date());
			user.setUsername("thinhpt");
			user.setPassword("123456");
			txn = session.beginTransaction();
			session.save(user);
			txn.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
			if (txn != null) {
				txn.rollback();
				txn=null;
			}
		} finally {
			if (session != null) {
				session.close();
				session=null;
			}
		}

	}

And this is code of HibernateUtil

public class HibernateUtil {
	private static SessionFactory sf;

	private synchronized static void init() {
		if (sf == null) {
			try {
				Configuration cfg = new Configuration().configure();
				StandardServiceRegistryBuilder serviceRegistry = new StandardServiceRegistryBuilder()
						.applySettings(cfg.getProperties());
				sf = cfg.buildSessionFactory(serviceRegistry.build());
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public static Session openSession() {
		init();
		return sf.openSession();
	}
}

Seem database connection not release when close hibernate session as Hibernate 3.x

Solution

In hibernate 4.3.5 to realease database connection we must close sessionFactory. So following is change of mine to make it work.

  • add release function to HibernateUtil class to close sessionFactory
     public static void release() {
		sf.close();
	}
   
  • call it on finally block on main function

Leave a Reply