42

Problem: I need to implement object cache. The cache need to be thread-safe and need to populate values on demand(lazy loading). The values are retrieved via web service by Key(slow operation). So I've decided to use ConcurrentDictionary and its GetOrAdd() method that has a value factory method supposing that the operation is atomic and synchronized. Unfortunately I found the following statement in the MSDN article: How to: Add and Remove Items from a ConcurrentDictionary:

Also, although all methods of ConcurrentDictionary are thread-safe, not all methods are atomic, specifically GetOrAdd and AddOrUpdate. The user delegate that is passed to these methods is invoked outside of the dictionary's internal lock.

Well that's unfortunate but still doesn't answer my answer completely.

Question: Is value factory invoked only once per key? In my specific case: Is it possible that multiple threads that are looking for the same key spawning multiple request to the web service for the same value?

1
  • 2
    No, use a CD<Key, Lazy<Value>>. That's the standard pattern.
    – usr
    Jul 26, 2015 at 13:32

3 Answers 3

59

As others have already pointed out, valueFactory may be invoked more than once. There is a common solution that mitigates this issue - have your valueFactory return a Lazy<T> instance. Although it's possible that multiple lazy instances will be created, the actual T value will only be created when you access Lazy<T>.Value property.

Specifically:

// Lazy instance may be created multiple times, but only one will actually be used.
// GetObjectFromRemoteServer will not be called here.
var lazyObject = dict.GetOrAdd("key", key => new Lazy<MyObject>(() => GetObjectFromRemoteServer()));

// Only here GetObjectFromRemoteServer() will be called.
// The next calls will not go to the server
var myObject = lazyObject.Value;

This method is further explained in Reed Copsey's blog post

7
  • Sorry, my bad. I initially thought GetOrAdd would return the value created by valueFactory, so two GetOrAdd calls could return two different results (like the first commenter in your linked post). After a second thought, this would be totally stupid. This solution works. Jul 26, 2015 at 15:47
  • 12
    This approach does not guarantee that the factory method will be called once. The fact is that Lazy<T> is created synchronously and is cheap, so it is harder for race conditions to occur, but they could still occur.
    – BladeWise
    Feb 18, 2019 at 10:22
  • 2
    @BladeWise how so? GetOrAdd will always return value that is actually in the collection (so always the same value), then Lazy.Value will invoke the factory method only once Mar 18, 2020 at 10:54
  • 2
    @Taudris The instance of Lazy<T> returned by GetOrAdd for a given key will be the same across all GetOrAdd invocations. Therefore the race condition cannot occur. Parallel invocations of GetOrAdd which are creating new values for a given key are linearizable as follows: The first GetOrAdd invocation to create the value stores it in the collection. All other GetOrAdd invocations create their values and discard them, returning the value already stored in the collection. Sep 27, 2021 at 22:41
  • 1
    So even though multiple threads can end up creating Lazy<T> instances, only one instance ever gets stored, and that's the one that all threads will return. It seems you are correct; I'll remove my comment.
    – Taudris
    Sep 28, 2021 at 14:08
36

Is value factory invoked only once per key?

No, it isn't. The docs say:

If you call GetOrAdd simultaneously on different threads, valueFactory may be invoked multiple times, but its key/value pair might not be added to the dictionary for every call.

0
20

Let's take a look at the source code of GetOrAdd:

public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
    if (key == null) throw new ArgumentNullException("key");
    if (valueFactory == null) throw new ArgumentNullException("valueFactory");

    TValue resultingValue;
    if (TryGetValue(key, out resultingValue))
    {
        return resultingValue;
    }
    TryAddInternal(key, valueFactory(key), false, true, out resultingValue);
    return resultingValue;
}

Unfortunately, in this case, it's clear nothing guarantees that valueFactory won't be called more than once, if two GetOrAdd invocations happen to run in parallel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.