Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a read-only HashSet inherently threadsafe?

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).

like image 327
Samuel Neff Avatar asked Nov 25 '14 15:11

Samuel Neff


People also ask

Is HashSet read thread-safe?

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.

Is read-only thread-safe?

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.

Is HashSet synchronized Java?

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.

Is HashSet thread-safe in Java?

Most of the collections such as ArrayList, LinkedList, HashSet, HashMap, etc., are not thread-safe.


1 Answers

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
                                 );
like image 130
Patrick Hofman Avatar answered Oct 04 '22 18:10

Patrick Hofman