#944 – Lazy Instantiation, Solution #2

The previous post showed one way to achieve lazy instantiation–waiting to initialize a data object until just before it’s needed.  The problem with this example, however, was that it wasn’t thread-safe.  Two threads could simultaneously check to see if the object is initialized and both determine that it is not.  Both threads would then try to initialize the object.

The code below updates the earlier example, making it thread-safe.

        private static List listOfAllFamousDogs = null;
        private static readonly object initLock = new object();

        private static List GenerateBigListOfFamousDogs()
        {
            Console.WriteLine("Loading big list of famous dogs!");
            List bigList = new List();
            bigList.Add(new Dog("Lassie"));
            bigList.Add(new Dog("Rin Tin Tin"));
            // load 1,000 more dogs here

            return bigList;
        }

        public bool IsFamous
        {
            get
            {
                lock (initLock)
                {
                    if (listOfAllFamousDogs == null)
                        listOfAllFamousDogs = GenerateBigListOfFamousDogs();
                }

                return listOfAllFamousDogs.Contains(this);
            }
        }

Next time, we’ll see an easier way to do this in .NET 4.0 or later.

Advertisements