#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
                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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #944 – Lazy Instantiation, Solution #2

  1. Pingback: Dew Drop – October 3, 2013 (#1,637) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: