Which Java Collections are synchronized, which are not?
Example: HashSet is not synchronized
Most of the Collections classes objects (like ArrayList, LinkedList, HashMap etc) are non-synchronized in nature i.e. multiple threads can perform on a object at a time simultaneously. Therefore objects are not thread-safe.
The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.
Do you notice that all the basic collection classes - ArrayList, LinkedList, HashMap, HashSet, TreeMap, TreeSet, etc - all are not synchronized? In fact, all collection classes (except Vector and Hashtable) in the java. util package are not thread-safe.
Non synchronized -It is not-thread safe and can't be shared between many threads without proper synchronization code. While, Synchronized- It is thread-safe and can be shared with many threads.
There are three groups of Collections.
Collections.synchronizedXxx()
methodsIn short, none of the collections I would recommend you use are synchronized.
Thread safe Collections -
Thread safe without having to synchronize the whole map Very fast reads while write is done with a lock No locking at the object level Uses multitude of locks.
Object level synchronization Both read and writes acquire a lock Locking the collection has a performance drawback May cause contention
Vector
HashTable
CopyOnWriteArrayList
CopyOnWriteArraySet
Stack
Rest all are not thread safe
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