Hibernate AssertionFailure in different Threads

14,607

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.

Share:
14,607

Related videos on Youtube

bladepit
Author by

bladepit

Updated on June 04, 2022

Comments

  • bladepit
    bladepit almost 2 years

    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?

  • bladepit
    bladepit over 11 years
    ok...this solution is the easy and right way i think. but all threads are working successive so i think one session is enough. is there no way to do it with one session?
  • Maciej Dragan
    Maciej Dragan over 11 years
    Not really. It's designed this way. From the doc: "The lifecycle of a Session is bounded by the beginning and end of a logical transaction". In Web apps this is often extended to multiple transactions but sill within one thread (request).
  • bladepit
    bladepit over 11 years
    i also never close the session after a thread is finished. is it better to do it always and open the session if i need it?
  • Maciej Dragan
    Maciej Dragan over 11 years
    Correct. Look at the example in the JavaDoc. Session is being closed in finally block.
  • bladepit
    bladepit over 11 years
    Thank you. Now i have to refactor it...:-) but it is needed for a correct working program...