Is it good to test a condition then lock then re-test the condition [duplicate]
-
15-11-2019 - |
Question
Possible Duplicate:
Double-checked locking in .net
EDIT: lots of edits to clarify this question is not about singleton
I find myself writing code like this:
if(resourceOnDiskNeedsUpdating)
{
lock(lockObject)
{
if(resourceOnDiskNeedsUpdating) // has a previous thread already done this?
UpdateResourceOnDisk();
}
}
return LoadResourceFromDisk();
UpdateResource()
is a slow operation.
Does this pattern make sense?
Are there better alternatives?
Solution
This called "double-checked locking".
You need a memory fence to make it correct.
OTHER TIPS
An alternative I use would be to just use the 'volatile' keyword. http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow