Is a read-only HashSet inherently threadsafe?

前端 未结 1 1389
暗喜
暗喜 2021-01-11 12:58

If I initialize a HashSet<> inside a Lazy initializer and then never change the contents, is that HashSet<> inherently thr

相关标签:
1条回答
  • 2021-01-11 13:11

    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 the Lazy<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
                                     );
    
    0 讨论(0)
提交回复
热议问题