1

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?

3
  • in my case the Update resource is writing a file on disk, if that makes any difference. Commented Feb 18, 2011 at 0:58
  • I've made my question NOT about singletons, is it still a duplicate? should I try re-open it ? :-} Commented Feb 18, 2011 at 1:50
  • Yes, it's still a duplicate. The other question also was about DCL in general, most of the answers gave examples using singletons, because that's where DCL commonly appears, but there's no difference in scope between the questions. Commented Feb 18, 2011 at 1:59

2 Answers 2

4

This called "double-checked locking".

You need a memory fence to make it correct.

See Wikipedia's article on double checked locking in .NET

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Well, given your edit - make the variable 'resourceNeedsUpdating' volatile and do away with the secondary check in the lock. Add a variable indicating whether or not you're in the process of updating and check it before checking resourceNeedsUpdating / set it before/after calling UpdateResource, or unset resourceNeedsUpdating before calling UpdateResource.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.