Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is Java HashSet thread-safe for read only?

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.

like image 503
Asaf Mesika Avatar asked Mar 21 '11 15:03

Asaf Mesika


People also ask

Is HashSet thread-safe in Java?

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.

Does HashSet contain thread-safe?

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.

Which collections are thread-safe in Java?

The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.

Is TreeSet thread-safe?

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.


2 Answers

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.

like image 69
Brian Roach Avatar answered Sep 21 '22 11:09

Brian Roach


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.

like image 45
Mark Peters Avatar answered Sep 19 '22 11:09

Mark Peters