If I initialize a HashSet<>
inside a Lazy
initializer and then never change the contents, is that HashSet<>
inherently threadsafe? Are there read actions that require locking?
Similar Java question here for collections generally, which essentially says yes, but with some caveats (that don't apply in this situation).
Threadsafe Collections. The collection interfaces in Java – List, Set, Map – have basic implementations that are not threadsafe. The implementations of these that you've been used to using, namely ArrayList, HashMap, and HashSet, cannot be used safely from more than one thread.
The Regex class itself is thread safe and immutable (read-only). That is, Regex objects can be created on any thread and shared between threads; matching methods can be called from any thread and never alter any global state.
ArrayList, HashSet and HashMap are three most frequently used data structures in java. As they are most used, they are not synchronized for the sake of performance.
Most of the collections such as ArrayList, LinkedList, HashSet, HashMap, etc., are not thread-safe.
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With