6
votes

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?

2
i clicked the upvote sign. - Farhan Shirgill Ansari

2 Answers

1
votes

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.

1
votes

Yes. SessionFactory is immutable and thus, thread safe.