Hi there,
Right now I'm thinking about accessing the same DB from two different threads in one windows service via NHibernate 1.2.1 GA. The docs say to never open two ISessions for the same DB at the same time (stale data) and to never access one ISession from two concurrent Threads
Now my scenario currently has a singleton Sessionmanager that keeps track of the sessions currently open. If i request a Session from the Sessionmanager for a particular database it is enforced that there will be only one ISession opened per database.
If I add another thread to the application then two threads will receive the same ISession object and there the troubles are going to start presumably.
I found three ways that were suggested some time ago in this board.
a: open one ISession per database query.
First thing that will break is lazily loading collections on demand somewhere in some upper layer. I guess more things are to follow.
b: open one ISession per thread
Well this breaks the rule to not open more than one ISession per Database. If this is only for preventing stale Data I wouldn't have to worry much as things already have to be designed with things like stale or missing data in mind. The threads will also not interact with each other.
c: lock the ISession object on every query, update etc. so that it is used across threads but only once at the same time.
Things won't break but maybe performance suffers here. I'd have to refactor some things in the Sessionmanager and DAO's to eliminate repetition of code.
Now when I take approach c and lock the ISession I'd place locks like this around the write operations.
Code:
lock(objSession)
{
objSession.SaveOrUpdate(someObject);
}
Read operations are done via ICriteria queries all the time so I suspect I'd need only to do it like this
Code:
lock(objSession)
{
objCriteria = objSession.CreateCriteria(...);
}
and then proceed to use the lcriteria objects without locking.
Or do I need to lock the lSession object while calling the lcriteria.List<>() methods too?
I haven't decided on either b or c but "one session per query" is something that just doesn't really fit in the picture.
Geez the posting has gotten pretty long by now but what do you think about this ?