Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 852
Ievgen Avatar asked Sep 24 '14 15:09

Ievgen


People also ask

Is Lazy thread safe?

By default, Lazy<T> objects are thread-safe. That is, if the constructor does not specify the kind of thread safety, the Lazy<T> objects it creates are thread-safe.

Is lock thread safe C#?

The lock statement is one of the simplest and most common tools for C# developers writing multithreaded applications. It can be used to synchronize access to blocks of code, achieving thread safety by allowing only one thread at a time to execute the code in that block.

What does lock () do in C#?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

How might you ensure that only one thread at a time executes a particular method?

The synchronized keyword can be used to ensure that only one thread at a time executes a particular section of code. This is a simple way to prevent race conditions, which occur when several threads change shared data at the same time in a way that leads to incorrect results.


1 Answers

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.

like image 144
Servy Avatar answered Oct 07 '22 21:10

Servy