ConcurrentDictionary: Thread Safety Is Not Workflow Atomicity
Separate atomic dictionary operations from multi-step workflows.
What ConcurrentDictionary<TKey,TValue> makes atomic and what it does not: single operations are safe from any thread, but a sequence of calls, a value factory or an invariant across keys still needs its own design.
At a glance
- Each single operation (
TryAdd,TryGetValue,TryUpdate,TryRemove) is atomic and thread-safe; reads take no lock. - Two calls in a row are not atomic:
if (!d.ContainsKey(k)) d[k] = v;can run twice for the same key. GetOrAddandAddOrUpdatecall your delegates outside the dictionary's locks, so a delegate can run more than once and its extra results are thrown away: racingGetOrAddcalls store one value, and eachAddOrUpdatecall stores one result.- To run expensive work once per key, store a
Lazy<Task<T>>instead of the value. - No method updates two keys at once or keeps the dictionary in step with a database.
- Enumerating is safe while others write, but it is not a snapshot.
Which calls are atomic
| Call | Atomic? | Note |
|---|---|---|
TryAdd, TryGetValue, TryRemove(key, out value) | yes | the basic operations |
TryUpdate(key, newValue, comparisonValue) | yes | a compare-and-swap on one key |
TryRemove(KeyValuePair<TKey,TValue>) | yes | removes only if the key still has that value |
GetOrAdd(key, factory) | the insert is | the factory can run more than once; use the value it returns |
AddOrUpdate(key, add, update) | the store is | both delegates can run more than once |
ContainsKey then the indexer | no | two operations: another thread can act in between |
Count, Keys, Values, ToArray() | yes | they take all the locks, so they are costly in hot paths |
The factory can run twice
using System.Collections.Concurrent;
var cache = new ConcurrentDictionary<string, string>();
using var bothInside = new Barrier(2);
int factoryRuns = 0;
string Factory(string key)
{
int run = Interlocked.Increment(ref factoryRuns);
bothInside.SignalAndWait(); // both callers are inside the factory at once
return $"{key}: value {run}";
}
Task<string> a = Task.Run(() => cache.GetOrAdd("item-7", Factory));
Task<string> b = Task.Run(() => cache.GetOrAdd("item-7", Factory));
string[] results = await Task.WhenAll(a, b);
Console.WriteLine($"factory ran {factoryRuns} times");
Console.WriteLine($"both callers got the stored value: {results[0] == results[1] && results[0] == cache["item-7"]}");factory ran 2 times both callers got the stored value: True
- Both callers missed the key, so both ran the factory; one result was stored, and
GetOrAddreturned it to both. - A factory that sends an e-mail, charges a card or opens a connection must therefore not run inside
GetOrAdd.
Run the work once per key
public sealed class ItemCache(Func<string, Task<string>> loadAsync)
{
private readonly ConcurrentDictionary<string, Lazy<Task<string>>> items = new();
public Task<string> GetAsync(string key, CancellationToken waitToken = default) =>
items.GetOrAdd(key, k => new Lazy<Task<string>>(() => loadAsync(k))) // ExecutionAndPublication by default
.Value
.WaitAsync(waitToken); // cancels this caller's wait only
}- Several
Lazywrappers may be created, but only the stored one is read, and itsValuestarts the load once. - A failed task stays stored, so every later caller gets the same failure. To allow a retry, remove the entry with
TryRemove(KeyValuePair.Create(key, lazy)), which removes only that exact entry, not a newer one. - This keeps every key forever: bound the key set or add expiry before using it for keys that come from requests.
When the invariant spans more than one key
- One
lockthat every reader and writer of those keys takes, when the code is short and contention is low. - An immutable snapshot (
ImmutableDictionary, or aFrozenDictionaryrebuilt) swapped in withInterlocked.Exchange. - One owner for all the keys of the invariant, such as a single consumer that applies every change to them in order.
- A database transaction when the rule also covers stored data.
Common mistakes
ContainsKeyfollowed by an add or the indexer: useTryAddorGetOrAdd.- Side effects inside a
GetOrAddorAddOrUpdatedelegate: keep them out, or store aLazy<T>so they run once. - Ignoring the value
GetOrAddreturns and using the one your factory built: use the returned value. - Removing a failed entry by key alone: remove the exact key and value pair, or you may delete a newer entry.
- Calling
CountorKeysin a hot path: they take all of the dictionary's internal locks at once. If an approximate count is enough, keep your own counter withInterlocked; an exact count at one moment still needsCount. - Assuming thread safety covers a workflow across keys or with a database: design that atomicity separately.
In an interview
Is ConcurrentDictionary thread-safe? Each operation is. A sequence of operations is not one atomic step, and the delegates passed to GetOrAdd and AddOrUpdate run outside its locks.
Can the GetOrAdd value factory run more than once? Yes. When several threads miss the same key at once, each can run the factory; only one value is stored, and every caller gets that one.
How do you make sure an expensive load runs only once per key? Store a Lazy<Task<T>> (or Lazy<T>) and read its Value: extra wrappers may be created, but only the stored one runs. Decide what happens to failures and to one caller's cancellation.
How do you update a value atomically based on its old value? Use AddOrUpdate, whose update delegate may run more than once, or a loop: read the current value, compute the new one, call TryUpdate(key, newValue, current), and on failure read again; stop if the key was removed.
Is enumerating a ConcurrentDictionary safe while others write? Yes, it does not throw, but it is not a snapshot: it may show changes made during the enumeration. ToArray() returns a snapshot.
Check yourself
Two threads call GetOrAdd("k", Factory) at the same moment on an empty dictionary. What can happen?
Show answer
Correct answer: B
GetOrAdd calls the factory outside its locks, so both threads can run it; the first insert wins, and both callers get the stored value.
Option A: GetOrAdd alone does not promise one factory run; a stored Lazy<T> or your own coordination does.
Option C: A dictionary holds one value per key.
Option D: The losing call simply returns the value already stored.
Why is if (!cache.ContainsKey(k)) cache[k] = Load(k); unsafe under concurrency?
Show answer
Correct answer: B
Each call is safe on its own, but together they are two steps, so two threads can both see the key missing and both load.
Option A: ContainsKey is safe; the problem is the gap after it.
Option C: The indexer adds or replaces a value.
Option D: The two calls do not deadlock; the risk is that both threads load and one result overwrites the other.
A cached Lazy<Task<T>> holds a failed load. Which removal lets callers retry without deleting a newer entry?
Show answer
Correct answer: B
The key-and-value overload removes the entry only if it still holds that exact Lazy, so a replacement added meanwhile stays.
Option A: Removing by key alone can delete a newer, healthy entry.
Option C: Clearing removes every key, not only the failed one.
Option D: A null value is still an entry and breaks every reader.
Sources
- ConcurrentDictionary<TKey,TValue>: which operations are atomic; delegates run outside the locks.
- ConcurrentDictionary.GetEnumerator: safe while others write, not a moment-in-time snapshot.
- How to add and remove items from a ConcurrentDictionary:
AddOrUpdate,GetOrAddandTryUpdatein use. - LazyThreadSafetyMode:
ExecutionAndPublicationruns the factory once.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·