Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

is it safe to apply double-checked locking to Dictionary?

Is it safe to apply double-checked locking to Dictionary?

I.e. if it safe to call TryGetValue and other "get/contains" methods from different threads? (without calling other, non-get methods).

upd Would collection be safe for N readers AND 1 writer? Assume In cycle 10 threads are try to access element with key X using double-checked locking and if accessed they just remove it. At some point I do add element with key X from one another thread (using lock). I expect that exactly one reader should obtain this element and delete it.

upd2, about answer so my question is confusing. actually I've asked two questions:

  1. if it safe to call TryGetValue and other "get/contains" methods from different threads? (without calling other, non-get methods).
  2. Would collection be safe for N readers AND 1 writer?

The answer for first question is Yes and the answer for second question is No.

So sometimes it's safe to apply double-checked locking sometimes it is not. It depends on if you are writing at the same time to a collection.

Upvotes: 2

Views: 264

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134125

I assume you're talking about the generic Dictionary<TKey, TValue> class. That class is safe for N readers or 1 writer. So as long as you're not modifying it, you can have as many threads you want reading from it, no lock required.

If it's possible that a thread will want to modify the dictionary, you have to synchronize access to it. I would suggest ReaderWriterLockSlim.

Upvotes: 3

usr
usr

Reputation: 171246

This is not safe because it is not documented to be safe. You can't have one writer and N readers.

Here is an applicable sentence from the docs:

A Dictionary can support multiple readers concurrently, as long as the collection is not modified.

Actually, if you peek into Dictionary with Reflector you can see that it is unsafe, but that is not the point. The point is that you cannot rely on undocumented properties because they can change at any time, introducing bugs into production that nobody knows about.

You also cannot test this to be safe. It might work on your box and break somewhere else. This is the nature of threading bugs. Not worth it.

Upvotes: 1

Related Questions