ConcurrentDictionary + Lazy - is an instance created only once?

Scenario

Say we have:

var dictionary = new ConcurrentDictionary<string, Lazy<Heavy>>();

Activation is Heavyvery resource intensive. Consider this code:

return dictionary.GetOrAdd("key", key => 
{
    return new Lazy<Heavy>(() =>
    {
        return Instantiate();
    });
}).Value;

The method Instantiate(), of course, returns an instance of the type Heavy.

Question

Instantiate()Is it 100% guaranteed for this key that the method will be called no more than once ?

Sources

Some people claim that having multiple threads, we can only create a few instances Lazy<Heavy>, which is very cheap. The actual method Instantiate()will be called no more than once.

, . ?

+4
1

Instantiate . GetOrAdd :

GetOrAdd , addValueFactory , / .

: addValueFactory - GetOrAdd. , GetOrAdd - - 2 Lazy<Heavy>, GetOrAdd, ( factory - , , factory, , GetOrAdd). .Value GetOrAdd - Lazy<Heavy>, Instantiate .

+6

Source: https://habr.com/ru/post/1689825/


All Articles