Locking Resources

One issue often overlooked is concurrency issues.  I know in my development, I sometimes overlook this task.  But concurrency issues are important, especially with some data access layers like LINQ-to-SQL.  So how can this be prevented?  You can use an approach like the following:

public static class MyClass
{
   private static DataSet _data = null;
   private static object _lock = new object();

   public static DataSet GetData()
   {
      if (_data != null)
        return _data;

      lock(_lock)
      {
        //important to check twice; when the first lock is released, _data could be populated for subsequent locks
        if (_data != null)
          return _data;

         //Load the data from the data access layer
      }
   }
}

In this example, I used a static class, but this could be done in instance classes as well.  To lock the resource down, simply provide it an object; in books I've read, the approach above was used, but I've also seen an approach where someone uses a class type.  For more information about locking processes, see this:  http://msdn.microsoft.com/en-us/library/ms173179.aspx

It's important to check for the existence of the data twice; if two classes access this shared resource, the first process locks the resource, and populates the _data variable.  The second resource passed the first not null check, and is currently at the lock.  Without the second check after the lock, it would populate the _data variable again.  Rather, in this scenario, the second check finds that _data has been populated, and returns it.

Comments

No Comments