If I initialize a HashSet<>
inside a Lazy
initializer and then never change the contents, is that HashSet<>
inherently thr
Yes, it is. As long as the construction of the HashSet
object is thread safe, accessing it will always be thread safe as long as the contents doesn't change.
If you initialize the Lazy
using LazyThreadSafetyMode.PublicationOnly you can be sure the initialization of the Lazy
is thread safe.
When multiple threads try to initialize a
Lazy<T>
instance simultaneously, all threads are allowed to run the initialization method (or the default constructor, if there is no initialization method). The first thread to complete initialization sets the value of theLazy<T>
instance. That value is returned to any other threads that were simultaneously running the initialization method, unless the initialization method throws exceptions on those threads.
A little code sample:
var l = new Lazy<HashSet<string>>( () => new HashSet<string>() { "a" }
, LazyThreadSafetyMode.PublicationOnly
);