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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With