just random stuff

Using locks when caching objects

Who doesn't like to increase the performance of their web applications?  It was a bit over a year ago when I started working with .net's caching object collection to increase performance.  Here's some code:

 

 DataSet ds = new DataSet();
 object cachedItems = Cache["myItems"];
 if( cachedItems == null )
 {
   Cache["myResults"] = ds = 
                       dal.GetDatabaseResults(sqlstmt);
 }
 return ds;

 

But what happens if your site is getting hit with a heavy load and your query takes several seconds to return results?  The problem is that if 8 requests come in after the first request (which already launched the sql server request) you're losing out on a huge performance gain. 

In a recent article in msdn magazine by Richard Campbell and kent Alstad points out a great benefit when using locks during a cache check.  The code above could be rewritten as shown below:

 

 DataSet ds = new DataSet();
 object cachedItems = Cache["myItems"];
 
 if( cachedItems == null )
 {
   lock(lockobject)
   {
     if( cachedItems == null )
     {
        Cache["myResults"] = ds = dal.GetDatabaseResults(sqlstmt);
     }
   }
 }
return ds;

 

You'll notice the lock in the code which will prevent other threads from executing until the first thread completes it's retrieval from sql server.  However, you'll also notice the recheck of the cachedItems object.  This is so that those threads that checked for null and had been waiting for the lock to be released don't call the database again, rather they check the cachedItems object and see that it's populated and don't call sql.

Good defensive code.  Does anyone do things a little differently?

» Similar Posts

  1. Why aren't my other web apps working after installing Graffiti CMS at /[root]
  2. Territory import format
  3. Day 3 at Telligent

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://samdelagarza.com/trackback.ashx?id=16

» Comments

    There are no comments. Kick things off by filling out the form below.

» Leave a Comment