0

Does it make sense to store a NHibernate session within ThreadLocal, is it safe to assume that will be Thread Safe and would solve the lazy loading issues with sessions? Also is it safe to assume that Session will be available for as long as the thread is executing? In terms of thread I m talking about HttpRequet.

Moreover, Would I run out of sessions for NHibernate? Is there a max number of sessions? Would that be OK if I have many threads?

DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • What do you mean by this `Thread Safe and would solve the lazy loading issues with sessions` ? – Rippo Apr 25 '12 at 19:37
  • by lazy loading issue, if you refer an object that is Mapped for Lazy loading in the view, you will get session is closed exception. View Pattern. Thread Safe, do i get a session per thread? and no race condition will happen. – DarthVader Apr 25 '12 at 19:42
  • I have always been led to believe that the session factory is thread safe BUT sessions are not so using ThreadLocal is going to bite you later. – Rippo Apr 25 '12 at 20:37
  • yes, i m aware that sessions are not thread safe but why would ThreadLocal bite me? If i create a session per thread and store it in thread local is it bad? – DarthVader Apr 25 '12 at 20:57
  • I may have misread the MSDN description of ThreadLocal `ThreadLocal is thread-safe and may be used concurrently from multiple threads` – Rippo Apr 25 '12 at 21:11

1 Answers1

2

NHibernate session is not thread safe. As long as you have associate a single session with one session that should work ok.

If you are going for http requests the best way to use session per request implementation, where a session is open whenever a request is started and closed when request is ended. In this case it's safe to assume that session will be available for as long as the thread is executing.

Usually NHibernate would not run out sessions, however the better practice is to use a session with lowest possible lifespan.

Low Flying Pelican
  • 5,974
  • 1
  • 32
  • 43
  • makes sense and depends on number of connections u are getting, u might run out of connections. – DarthVader Apr 26 '12 at 06:25
  • @DarthVader: Session != Connection. You can have an arbitrary amount of nh session objects (only limited by the memory in your system) http://ayende.com/blog/4123/what-is-the-cost-of-opening-a-session. – Andreas Apr 26 '12 at 21:25