Double checked locking

G

Guest

This code uses lazy initialization and double checked locking to read urls
associated with a retailer from a map.

Will the code work? I'm not sure how volatile applies to references.

private static volatile Dictionary<string, string> urlMap_;
private static object syncRoot = new Object();

public static string GetUrl(string retailerId)
{
string url;
urlMap_.TryGetValue(retailerId, out url);

if (url == null)
{
lock (syncRoot)
{
urlMap_.TryGetValue(retailerId, out url);
if (url == null)
{
url = .. //somehow obtain the url
urlMap_.Add(retailerId, url);
}
}
}
return url;
}
 
B

Brian Gideon

Hi,

No, that code won't work. Sure it looks similar to the canonical
double-checked locking implementation in C#, but remember, the
canonical form deals with setting a reference to a single variable.
In that case there is complete control over how that variable is both
read and written. Contrast that with your code. You're not trying
initialize a Dictionary and assign a reference to a variable.
Instead, you're trying to add values to it. You have no control over
how Dictionary.Add and Dictionary.TryGetValue are implemented and what
may go wrong when executed simultaneously. Specifically, I'm
envisioning a scenario where the Dictionary is in the middle of growth
operation while TryGetValue is called.

Brian
 
J

Jon Skeet [C# MVP]

aindrei said:
This code uses lazy initialization and double checked locking to read urls
associated with a retailer from a map.

Will the code work? I'm not sure how volatile applies to references.

It's not clear from the docs whether it's safe to have *any* readers
while you've got a writer for Dictionary<K,V>, and that's what you'll
end up with using the code provided.

Any time you have to ask "is it safe?" about threading, the immediate
follow-up question should always be "how expensive would a simpler,
definitely-safe version be"? In this case, the simple version is to
always lock. Have you tried that and found you've got contention? If
obtaining the URL might take a long time, there are alternatives which
might risk fetching a URL twice but without blocking other readers.

I'd definitely steer clear of DCL unless you know you really, really
know you need something particularly cunning. That should be backed up
with profiler evidence, btw.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top