Search code examples
databasespring-boothibernateentitymanagerhikaricp

NullPointerException happening intermittently with Hibernate criteriaQuery


I am working on a springboot application in a multi-threading environment where I am using Hibernate with javax.persistence.EntityManager to access database. I have separate HikariPools for read and write queries.

Here, the multiple threads while doing read operation from database (all the read queries) are using a single read connection (since I have autowired the entityManager and not using PersistanceContext). And similarly multiple threads will write to db as well with the help of writeEntityManager where a single connection is being used by all of the threads.

I am facing an issue with AbstractLockUpgradeEventListener.upgradeLock . This is happening intermittently and could not find the exact root cause for this.

Few assumptions:-

  • DB utilization touches 100%.( That might give an edge to this issue)
  • Lock is applied before executing any write query and threads are getting starved if one thread takes more than enough time

Attached the screenshot of the complete exception trace.

Can anyone suggest something here w.r.t design or implementation strategy or on what could be the actual root cause.

This only happens once in a while


Solution

  • The Hibernate EntityManager is not thread-safe, you must not use it from multiple threads.

    In fact the EntityManager AND the objects loaded must not be used from multiple threads

    https://discourse.hibernate.org/t/hibernate-and-multithreading/289