Hibernate Oracle sessions not be closed correctly
We got escalation today, a lot of services are very slow or stop working. Our Oracle database(10g) admin has found that there are a huge number of unclosed sessions in the Oracle database. In the services, Hibernate and the JDBC thin client were used.
The code looks as follows and the session has been closed manually after the transition. In the service there are only Readonly queries and no data change commit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Session session = null; Transaction transaction = null; EntityManager entityManager = entityManagerFactory.createEntityManager(); try { transaction = entityManager.getTransaction(); transaction.begin(); /* Do some query */ } catch (Exception exp) { exp.printStackTrace(); } finally { if (entityManager != null) { entityManager.close(); } } |
So why there are still so many unclosed sessions? After doing some research we found that this issue was caused by a transaction commit probably. Hibernate forces to COMMIT a transaction even in a query statement, otherwise, the session can not be closed.
https://stackoverflow.com/questions/46231089/hibernate-doesnt-close-connections-sessions-on-db
Depending on this, we changed the code to commit transactions and close sessions:
1 2 3 4 5 6 7 8 9 10 |
.......... finally { if (transaction != null && transaction.isActive()) { transaction.commit(); } if (entityManager != null && entityManager.isOpen()) { entityManager.close(); } } |
Reference:
https://stackoverflow.com/questions/57304210/java-hibernate-sessions-dont-get-killed-correctly
https://docs.oracle.com/cd/E28280_01/apirefs.1111/e13946/ejb3_overview_emfactory_close.html
https://stackoverflow.com/questions/46231089/hibernate-doesnt-close-connections-sessions-on-db
https://lists.jboss.org/pipermail/hibernate-users/2010-November/000096.html