Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is SessionFactory.getCurrentSession() thread safe?

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?

like image 882
Ali Avatar asked Feb 26 '14 02:02

Ali


People also ask

Is SessionFactory a thread safe object?

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.

What is SessionFactory getCurrentSession ()?

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>

Which Hibernate interface is not thread safe?

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.

Is Hibernate entity thread safe?

So NO: Hibernate Entities are not thread safe.


1 Answers

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.

like image 141
nachokk Avatar answered Oct 21 '22 17:10

nachokk