Ievgen
Ievgen

Reputation: 4443

Lazy loading without locks in multithread application

What will happen if two threads read this property at the same time?

public static HugeType HugeType
{
    get
    {
        if (tenderCache == null)
        {
            tenderCache = Config.Get<HugeType>("HugeType", null);
        }
        return tenderCache;
    }
}

My object is read only and it's not critical if two instances are created. Should I add locks in any case?

Upvotes: 10

Views: 924

Answers (1)

Servy
Servy

Reputation: 203834

Because you have no synchronization it's possible for the initialization method to be called many times, possibly even if other threads have completed the initialization entirely (due to a lack of a memory barrier). If you don't care about executing the initialization operation multiple times and it will always return the same correct value regardless of how many times it's called and even if multiple calls to it are made concurrently, then the code will certainly work, even if it won't perform as well.

Having said that, actually properly ensuring that the initialization is only done once is very easy, given that it's already a solved problem. You can simply store a Lazy<HugeType> in your field instead of a HugeType and Lazy will take care of the initialization synchronization for you.

Upvotes: 10

Related Questions