Eugenio Valeiras Eugenio Valeiras - 6 months ago 111
Java Question

Hibernate throw "org.hibernate.exception.JDBCConnectionException: Could not open connection" Randomly in a Multi-Thread application

public class HibernateUtil {

private static SessionFactory INSTANCE_SESSION_FACTORY = null;

public enum Common {
SUCCESS, ROLLBACK
}

private synchronized static void createSessionFactory() {
try {
if (INSTANCE_SESSION_FACTORY != null) {
return;
}
ResourceBundle rb = ResourceBundle.getBundle("application");
Integer environment = Integer.valueOf(rb.getString("environment"));

Properties prop = new Properties();

switch (environment) {
/* LOCAL */
case 1:
prop.setProperty("hibernate.connection.driver_class", rb.getString("hibernate.driver.class.name"));
prop.setProperty("hibernate.connection.url", rb.getString("hibernate.db.uri"));
prop.setProperty("hibernate.connection.username", rb.getString("hibernate.db.username"));
prop.setProperty("hibernate.connection.password", rb.getString("hibernate.db.password"));
break;
default:
throw new ConfigurationException(environment == null ? "No environment added in application.properties"
: "Wrong environment added in application.properties");
}

prop.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
prop.setProperty("hibernate.show_sql", "true");
prop.setProperty("hibernate.hbm2ddl.auto", "update");
prop.setProperty("hibernate.current_session_context_class", "thread");
prop.setProperty("hibernate.connection.pool_size", "100");

prop.setProperty("hibernate.c3p0.minPoolSize", "5");
prop.setProperty("hibernate.c3p0.maxPoolSize", "100");
prop.setProperty("hibernate.c3p0.initialPoolSize", "10");
prop.setProperty("hibernate.c3p0.timeout", "1800");
prop.setProperty("hibernate.c3p0.max_statements=", "50");

org.hibernate.cfg.Configuration config = new org.hibernate.cfg.Configuration().addProperties(prop)
.addAnnotatedClass(Account.class).addAnnotatedClass(InsynctiveProperty.class)
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
.buildServiceRegistry();
INSTANCE_SESSION_FACTORY = config.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
if (INSTANCE_SESSION_FACTORY == null) {
createSessionFactory();
}
return INSTANCE_SESSION_FACTORY;
}

public static Session getCurrentSession() {
return getSessionFactory().getCurrentSession();
}

public static Session openSession() {
return getSessionFactory().openSession();
}

public static void closeCurrentSession() {
getSessionFactory().getCurrentSession().close();
}

public synchronized static Object get(Class<?> clazz, Integer id) {
Session session = getCurrentSession();
final Transaction transaction = session.beginTransaction();
try {
Object obj = session.get(clazz, id);
transaction.commit();
return obj;
} catch (RuntimeException ex) {
System.out.println(ex);
transaction.rollback();
throw ex;
} finally {

}
}

public Common save(Object object) {
Session session = openCurrentSession();
Transaction transaction = null;
Common result = null;
try {
transaction = openTransaction(session);
session.save(object);
transaction.commit();
result = Common.SUCCESS;
} catch (Exception e) {
e.printStackTrace();
if (transaction != null) {
transaction.rollback();
}
result = Common.ROLLBACK;
} finally {
session.close();
}

return result;
}

public Common update(Object object) {
Session session = openCurrentSession();
Transaction transaction = null;
Common result;

try {
transaction = openTransaction(session);
session.update(object);
transaction.commit();
result = Common.SUCCESS;
} catch (Exception e) {
e.printStackTrace();

if (transaction != null) {
transaction.rollback();
}
result = Common.ROLLBACK;
} finally {
session.close();
}
return result;
}

public Session openCurrentSession() {
return getSessionFactory().openSession();
}

public Transaction openTransaction(Session session) {
return session.beginTransaction();
}
}


Sometimes when a use one of these mehtods I recive this error:


org.hibernate.exception.JDBCConnectionException: Could not open connection

[org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131),
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49),
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125),
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110),
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304),
org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169),
org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doBegin(JdbcTransaction.java:67),
org.hibernate.engine.transaction.spi.AbstractTransactionImpl.begin(AbstractTransactionImpl.java:160),
org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1396),
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43),
java.lang.reflect.Method.invoke(Method.java:483),
org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352),
com.sun.proxy.$Proxy66.beginTransaction(Unknown Source),
insynctive.utils.HibernateUtil.get(HibernateUtil.java:123),
insynctive.tests.TestMachine.tearUp(TestMachine.java:104),
insynctive.tests.PersonFileTest.tearUp(PersonFileTest.java:52),
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62),
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43),
java.lang.reflect.Method.invoke(Method.java:483),
org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85),
org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:517),
org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213),
org.testng.internal.Invoker.invokeConfigurations(Invoker.java:140),
org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:170),
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:104),
org.testng.TestRunner.privateRun(TestRunner.java:771),
org.testng.TestRunner.run(TestRunner.java:621),
org.testng.SuiteRunner.runTest(SuiteRunner.java:357),
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352),
org.testng.SuiteRunner.privateRun(SuiteRunner.java:310),
org.testng.SuiteRunner.run(SuiteRunner.java:259),
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52),
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86),
org.testng.TestNG.runSuitesSequentially(TestNG.java:1199),
org.testng.TestNG.runSuitesLocally(TestNG.java:1124),
org.testng.TestNG.run(TestNG.java:1032),
insynctive.runnable.RunnableTest.run(RunnableTest.java:15),
java.lang.Thread.run(Thread.java:745)]


SQLStateConversionDelegate.java:131

else if ( CONNECTION_CATEGORIES.contains( sqlStateClassCode ) ) {
return new JDBCConnectionException( message, sqlException, sql );


And I need to restart the pool sessions to continue working..

Any idea whats happens?
My application is a Multi Thread application, I throw like 6-10 threads.

Note
I'm using a Heroku DB (ClearDB MySQL) when I used a local DB i cant reproduce this error.

Answer

You have implemented the double checked locking pattern. in order for it to work correctly, you must make the INSTANCE_SESSION_FACTORY variable volatile.

note, that may or may not be the cause of the exception, but it is certainly a bug in your code.

UPDATE:

It's possible you are simply running into scenarios where your pooled connections have timed out. you might want to try enabling c3p0's idle connection checking (something like "idleConnectionTestPeriod=300").