How to show that the double-checked-lock pattern with Dictionary's TryGetValue is not threadsafe in
Posted
by Amir
on Stack Overflow
See other posts from Stack Overflow
or by Amir
Published on 2010-04-12T18:15:19Z
Indexed on
2010/04/12
18:42 UTC
Read the original article
Hit count: 355
Recently I've seen some C# projects that use a double-checked-lock pattern on a Dictionary
. Something like this:
private static readonly object _lock = new object();
private static volatile IDictionary<string, object> _cache =
new Dictionary<string, object>();
public static object Create(string key)
{
object val;
if (!_cache.TryGetValue(key, out val))
{
lock (_lock)
{
if (!_cache.TryGetValue(key, out val))
{
val = new object(); // factory construction based on key here.
_cache.Add(key, val);
}
}
}
return val;
}
This code is incorrect, since the Dictionary
can be "growing" the collection in _cache.Add()
while _cache.TryGetValue
(outside the lock) is iterating over the collection. It might be extremely unlikely in many situations, but is still wrong.
Is there a simple program to demonstrate that this code fails?
Does it make sense to incorporate this into a unit test? And if so, how?
© Stack Overflow or respective owner