Is it thread safe to obtain a Hibernate session via SessionFactory.getCurrentSession()?
Suppose I have one static SessionFactory object which is used for my entire app, and I have 5 concurrent requests being made to my servlet. My servlet calls the method Auth.checkLogin() for each of those requests, and Auth.checkLogin() in turn obtains a session via the static factory.getCurrentSession().
At the end of each of the requests to my servlet, transaction.commit() is called on the session which was previously obtained.
My question is, is this a thread safe method? Or should I make any changes?
The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.
Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file like below. <property name="hibernate.current_session_context_class">thread</property>
23) Does Hibernate Session interface is thread-safe in Java? No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.
So NO: Hibernate Entities are not thread safe.
From Hibernate 4.0 SessionFactory
The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
Implementors must be threadsafe.
So then
Is it thread safe to obtain a Hibernate session via SessionFactory.getCurrentSession()?
For what api says then Yes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With