Which Java Collections are synchronized, which are not?
Example: HashSet is not synchronized
You can get a synchronized version of a Java Collection
with
Collections.synchronizedCollection(Collection<T> c)
[javadoc]
ArrayList, LinkedList, HashSet,LinkedHashset and TreeSet in Collection Interface and HashMap,LinkedHashMap and Treemap are all non-synchronized.
Vector in Collection Interface is Synchronized
I guess each implementation of collection API has it written in documentation.
All collection classes (except Vector and Hashtable) in the java.util package are not thread-safe. The only two legacy collections are thread-safe: Vector and Hashtable. WHY? Here’s the reason: Synchronization can be very expensive! You know, Vector and Hashtable are the two collections exist early in Java history, and they are designed for thread-safe from the start (if you have chance to look at their source code, you will see their methods are all synchronized!). However, they quickly expose poor performance in multi-threaded programs. As you may know, synchronization requires locks which always take time to monitor, and that reduces the performance. That’s why the new collections (List, Set, Map, etc) provide no concurrency control at all to provide maximum performance in single-threaded applications.
Easy answer: not a single implementation of Collection
is synchronized because synchronized
is not a class property, it is only applicable to methods and blocks.
I guess, you want to know which implementations are thread safe, which classes from the java collection framework can safely be used in a multithreaded environment.
The information is always included in the javadoc (like here: Arraylist - which is not thread safe)
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