Thread-safe lazy init pattern

The code below is not thread-safe:

class SomethingWithLazyProperty
{
        private OtherThing otherThing = null;
        public OtherThing OtherThing
        {
            get
            {
                if (this.otherThing == null)
                {
                    this.otherThing = new OtherThing();
                }
 
                return this.otherThing;
            }
        }
}

As You may see when two threads enter the getter and the thread switching occures while
both of them are inside the if block two OtherThings will be instantiated and only
one of them will be stored in private field for later uses.

You should use some locking mechanism to avoid this race condition. The appropriate mechanism
may depend on the heaviness of instantiation. Lets choose lock to get out something more
of this example:

class SomethingWithLazyProperty
{
        private object syncRoot = new object();

        private OtherThing otherThing = null;
        public OtherThing OtherThing
        {
            get
            {
                lock(syncRoot)
                {
                    if (this.otherThing == null)
                    {
                        this.otherThing = new OtherThing();
                    }
                }
 
                return this.otherThing;
            }
        }
}

Thread-safety now in place, but the code will be really slow because of
locking every time we use this property. Thread-safety was only important
once at the begining but we slowed down the code for the whole lifecycle!
Modify a little bit the body of getter:


            get
            {
                if (this.otherThing == null)
                {
                    lock(syncRoot)
                    {
                        if (this.otherThing == null)
                        {
                            this.otherThing = new OtherThing();
                        }
                    }
                }
 
                return this.otherThing;
            }

And voilá, the code is thread-safe and as fast as at the original!

4 thoughts on “Thread-safe lazy init pattern

Leave a Reply