I\'m upgrading my Hibernate to the latest version. With my old HibernateUtil.java
I had no problems but when upgrading it, the SessionFactory doesn\'t seem to c
You're right, there appears to be a bug in Hibernate 4.3.x in which a thread spawned by Hibernate's default connection pool doesn't get cleaned up on shutdown. I filed a bug here (please vote!):
https://hibernate.atlassian.net/browse/HHH-8896
Until it's fixed, you have two choices. You can add a method to your HibernateUtil and use it to force the connection pool to clean itself up at the end of your app's execution:
public static void stopConnectionProvider() {
final SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory;
ConnectionProvider connectionProvider = sessionFactoryImplementor.getConnectionProvider();
if (Stoppable.class.isInstance(connectionProvider)) {
((Stoppable) connectionProvider).stop();
}
}
This works, but it's ugly, hacky, uses a deprecated method, etc. The better solution would be to just use a "real" connection pool, like c3p0, which can be enabled just by adding the following properties to your hibernate.cfg.xml:
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.min_size">10</property>
<property name="hibernate.c3p0.timeout">100</property>
Note that if you use another connection pool, you should remove this connection pool property which is currently in your config:
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
Edit: to use c3p0 connection pooling you'll also need the hibernate-c3p0 dependency. Maven example for 4.3.0-SNAPSHOT from the Hibernate snapshots repo:
<repositories>
...
<repository>
<id>hibernate-snapshots</id>
<url>http://snapshots.jboss.org/maven2/</url>
</repository>
...
</repositories>
<dependencies>
...
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.0-SNAPSHOT</version>
</dependency>
...
<dependencies>
Release the serviceRegistry when the main application terminates.
public class Service {
private SessionFactory factory;
private ServiceRegistry serviceRegistry;
public void initialize() throws Exception{
Configuration configuration = new Configuration();
configuration.configure("com/jeecourse/config/hibernate.cfg.xml");
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
factory = configuration.buildSessionFactory(serviceRegistry);
}
public void close() throws Exception{
if(serviceRegistry!= null) {
StandardServiceRegistryBuilder.destroy(serviceRegistry);
}
}
The issue seems to be already solved in Hibernate version 4.3.5 .
sessionFactory.close();
works in my program.