Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    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.
    • GetOrAdd and AddOrUpdate call your delegates outside the dictionary's locks, so a delegate can run more than once and its extra results are thrown away: racing GetOrAdd calls store one value, and each AddOrUpdate call 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

    CallAtomic?Note
    TryAdd, TryGetValue, TryRemove(key, out value)yesthe basic operations
    TryUpdate(key, newValue, comparisonValue)yesa compare-and-swap on one key
    TryRemove(KeyValuePair<TKey,TValue>)yesremoves only if the key still has that value
    GetOrAdd(key, factory)the insert isthe factory can run more than once; use the value it returns
    AddOrUpdate(key, add, update)the store isboth delegates can run more than once
    ContainsKey then the indexernotwo operations: another thread can act in between
    Count, Keys, Values, ToArray()yesthey take all the locks, so they are costly in hot paths

    The factory can run twice

    C#Runs
    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"]}");
    Output
    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 GetOrAdd returned 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

    C#
    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 Lazy wrappers may be created, but only the stored one is read, and its Value starts 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 lock that every reader and writer of those keys takes, when the code is short and contention is low.
    • An immutable snapshot (ImmutableDictionary, or a FrozenDictionary rebuilt) swapped in with Interlocked.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

    • ContainsKey followed by an add or the indexer: use TryAdd or GetOrAdd.
    • Side effects inside a GetOrAdd or AddOrUpdate delegate: keep them out, or store a Lazy<T> so they run once.
    • Ignoring the value GetOrAdd returns 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 Count or Keys in a hot path: they take all of the dictionary's internal locks at once. If an approximate count is enough, keep your own counter with Interlocked; an exact count at one moment still needs Count.
    • 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?

    A The factory always runs exactly once
    B The factory may run twice; one value is stored
    C Both values are stored under "k"
    D The second call throws an exception
    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?

    A ContainsKey is not thread-safe
    B Another thread can add the key between the two calls
    C The indexer cannot set new keys
    D It always deadlocks
    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?

    A TryRemove(key, out _)
    B TryRemove(KeyValuePair.Create(key, failedLazy))
    C Clear()
    D Setting the indexer to null
    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

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·