Is it good to test a condition then lock then re-test the condition [duplicate]
Asked Answered
A

2

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?

Apsis answered 18/2, 2011 at 0:43 Comment(3)
in my case the Update resource is writing a file on disk, if that makes any difference.Apsis
I've made my question NOT about singletons, is it still a duplicate? should I try re-open it ? :-}Apsis
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.Poppyhead
P
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

Poppyhead answered 18/2, 2011 at 0:47 Comment(0)
S
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

Sympathizer answered 18/2, 2011 at 0:52 Comment(1)
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.Sympathizer

© 2022 - 2024 — McMap. All rights reserved.