Reputation: 25
Is it correct to use double check locking with not static fields?
class Foo
{
private SomeType member;
private readonly object memeberSync = new object();
public SomeType Memeber
{
get
{
if(member == null)
{
lock(memeberSync)
{
if(member == null)
{
member = new SomeType();
}
}
}
return object;
}
}
}
Upvotes: 3
Views: 145
Reputation: 75306
Is it correct to use double check locking with not static fields?
Yes, nothing wrong with your code to use double checking with lock
to get thread-safe and lazy loading. If you are using from .NET 4, it would be suggested using Lazy class, this approach get the same result with thread-safe and lazy loading but it also makes your code simpler, more readable.
class Foo
{
private readonly Lazy<SomeType> _member =
new Lazy<SomeType>(() => new SomeType());
public SomeType Member
{
get { return _member.Value; }
}
}
Upvotes: 6
Reputation: 34198
The outer check gives a performance boost in that, once member
is initialised, you don't have to obtain the lock every time you access the property. If you're accessing the property frequently from multiple threads, the performance hit of the lock could be quite noticeable.
The inner check is necessary to prevent race conditions: without that, it would be possible for two threads to process the outer if
statement, and then both would initialise member
.
Strictly speaking, the outer if
isn't necessary, but it's considered good practise and (in a heavily-threaded application) the performance benefit would be noticeable.
Upvotes: 2
Reputation: 1821
It is a practice recommended by some because your lock may not apply until another lock is released.
In this case two threads access the getter at the same time, the first one gets the lock and the second waits.
Once the first is finished, the second thread now has the lock.
In cases where this is possible, you should check to see if the variable has already been created by another thread before the current thread acquired lock.
Upvotes: 0