Hibernate Session and thread safety

2019-08-07 20:01发布

问题:

I am trying to understand the meaning of 'Hibernate session are not thread safe'. What I already know (please correct me if I am wrong):

  1. A session in non-JTA environment is saved in Thread Local. So it is bound to the current thread.
  2. Calling getCurrentSession() in a new thread will associate a new session with its own thread local.
  3. Suppose we share an entity between 2 threads (T1,T2), loaded in T1 and used in T2 we could have issues with lazy loading etc. because the sessions in T1 and T2 are different.

This explains what could go wrong when an entity is shared between different sessions.

What I fail to understand is the problems that could arise when a Session is shared between 2 or more threads. I know that methods in Session are not thread safe and can cause race conditions etc. but it is not clear how? I would greatly appreciate if someone could explain with example(s) or list down one or more scenarios to clarify.

Thanks in advance

回答1:

The Java memory model has very strict rules for:

  • inter-thread memory visibility
  • thread operations reordering

The Session object is not thread-safe, meaning it was never intended to be accessed by more than one thread. For this it uses NO thread-safe mechanism:

  • no mutex
  • no volatile reads
  • no synchronization

If you were sharing a Hibernate Session between two threads, then one thread changes might not be visible to some other thread (without proper synchronization or volatile reads).

Each Hibernate Session gets an associated JDBC Connection (even JTA aggressive release end-up reusing the same JDBC connection for all statements issued by one JTA transaction DataSource). A JDBC Connection shouldn't be accessed by two threads, because each thread should be bound to a one and only one database transaction.