If I have an instance of an HashSet after I ran it through Collections.unmodifiableSet(), is it thread-safe?
I'm asking this since Set documentation states that it's not, but I'm only performing read operations.
Thread Safe HashSet Using ConcurrentHashMap Factory Method Basically, this method returns an instance that respects the java. util. Set interface and allows the usage of standard methods like add(), contains(), etc.
Since Contains does not modify the collection, it is merely a reading operation, and since HashSet is in System. Collections. Generic , calling Contains concurrently is absolutely fine.
The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
TreeMap and TreeSet are not thread-safe collections, so care must be taken to ensure when used in multi-threaded programs. Both TreeMap and TreeSet are safe when read, even concurrently, by multiple threads.
From the Javadoc:
Note that this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally
Reading doesn't modify a set, therefore you're fine.
HashSet
will be threadsafe if used in a read-only manner. That doesn't mean that any Set that you pass to Collections.unmodifiableSet()
will be threadsafe.
Imagine this naive implementation of contains
that caches the last value checked:
Object lastKey; boolean lastContains; public boolean contains(Object key) { if ( key == lastKey ) { return lastContains; } else { lastKey = key; lastContains = doContains(key); return lastContains; } }
Clearly this wouldn't be threadsafe.
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