Click here to Skip to main content
15,889,116 members
Articles / .NET

Demystifying concurrent lazy load pattern

Rate me:
Please Sign up or sign in to vote.
5.00/5 (13 votes)
5 Aug 2012CPOL9 min read 43K   581   29  
Shows what are common mistakes in lazy load implementations and how to implement fast concurrent lazy load cache.
using System.Collections.Generic;
using System.Threading;

namespace LazyLoadSample
{
	/// <summary>
	/// Base class for all cache implementations.
	/// </summary>
	public abstract class BaseCache
	{
		/// <summary>
		/// Gets the number of times data was loaded data loads.
		/// </summary>
		public int DataLoads { get; private set; }

		/// <summary>
		/// Gets or sets the time in milliseconds needed to load the data.
		/// </summary>
		public int TimeNeededToLoad { get; set; }

		/// <summary>
		/// Gets the products from cache.
		/// </summary>
		/// <returns>products from cache</returns>
		public abstract IList<Product> GetProducts();

		/// <summary>
		/// Resets the cache.
		/// </summary>
		public abstract void Reset();

		/// <summary>
		/// Loads the products from database.
		/// </summary>
		/// <returns>Products from database</returns>
		protected IList<Product> LoadProductsFromDatabase()
		{
			this.DataLoads++;
			Thread.Sleep(this.TimeNeededToLoad);

			// we are not going to hit a DB actually
			// to make example simpler
			IList<Product> list = new List<Product>();
			for (int i = 0; i < 10; i++)
			{
				list.Add(new Product());
			}

			return list;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) CallidusCloud
Serbia Serbia
I am a software developer at CallidusCloud currently working on software for Quoting and Product Configuration.

In past few years I have been working on development of multi-portal CMS and I was responsible for defining Coding standard and Code Review process. For three years, I have lead team of programmers that developed Soprex framework for enterprise applications development and I have also built Soprex Quotation Tool on that framework. My main points of interests are enterprise app architecture, Scrum and TDD.

I blogs about software development at www.Vukoje.NET.

Comments and Discussions