Deep Diving Into NHibernateThe Second Level Cache
I mentioned before that I am now part of the NHibernate project, but so far I haven't done much with it. In what turns out to be a nice timing, I found a fairly obscure bug that I hope that I can fix, and I am going to bore you with all the nitty gritty details of how I am going to do it.
Before I can begin, let me describe what area I am going to work at.
NHibernate has two level of caches. The first level is the session, which holds all the entities that were loaded (or saved) with the session. This cache is not shared among threads/requests. This cache hold the objects as fully instansiated entities, which mean that sharing them among threads/requests will cause multi threading issues.
The second level cache is shared among all the session that were created from the same session factory (typically, you only have a single session factory per application, so in essense, this is an application level cache). There are several targets to this second level cache, but the most common are:
- Hashtable cache (for debugging/testing purposes only)
- SysCache - which utilize the ASP.Net Cache
- Memcached - a distributed caching system
The second level cache does not hold entities, but collections of values. This means that you don't have to worry about mutli threading issues when you use this cache.
As far as I can see, the second level cache isn't very utilized in NHibernate projects, although I am not quite sure why this is the case, since it can give quite a performance boost to an application, without affecting the client code.