Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it thread safe to have a static IReadOnlyDictionary field?

Is it safe to write the following code?

private static readonly IReadOnlyDictionary<string, string> Map = new Dictionary<string, string>
{
    ["A"] = "AAA",
    ["B"] = "BBB",
    ["C"] = "CCC"
};

I know ConcurrencyDictionary is the standard way for achieving thread safety for dictionaries. But since all that I need is a "constant" map which I never intend to modify, is it 100% safe to initialize a readonly IReadOnlyDictionary static field?

like image 757
Lifu Huang Avatar asked Mar 06 '23 08:03

Lifu Huang


1 Answers

What matters for thread safety is the actual type of the object (Dictionary), not the type of the variable (IReadOnlyDictionary).

According to the documentation:

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

Therefore, your code is fine — assuming, of course, that no one casts your variable back to Dictionary and modifies it. If you're concerned about that possibility, then wrap your Dictionary in a ReadOnlyDictionary.

like image 165
Michael Liu Avatar answered Mar 10 '23 09:03

Michael Liu