Search code examples
javamultithreadinghibernateassertions

Hibernate AssertionFailure in different Threads


I connect to my database with one session. I have always the same session in my whole program. My Thread "1" catches primary data from the database. The user must be allowed to cancel this thread. So if the user presses the cancel button to often or to fast (this is my interpretation) the following error occures:

ERROR org.hibernate.AssertionFailure - HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session) 
org.hibernate.AssertionFailure: possible non-threadsafe access to the session

The same errors occures if i cancel my thread "2" which is running in the background after my thread "1" ist finished and the try to load another primary data set from the database.

Is the failure that i am using the same session in my two threads?

What is the right way to solve such a problem?


Solution

  • Each thread should obtain its own session from Hibernate session factory.

    It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from a SessionFactory.

    See here: Hibernate Session JavaDoc

    When you "cancel" a thread - it should do its own cleanup like transactions rollback, session close etc.