Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Java Collections are synchronized(thread safe), which are not?

Which Java Collections are synchronized, which are not?

Example: HashSet is not synchronized

like image 896
Enosh Bansode Avatar asked May 18 '11 13:05

Enosh Bansode


People also ask

Which collections are not thread-safe in Java?

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.

Which collection classes are synchronized or thread-safe?

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

Which collection classes are not synchronized?

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.

What is synchronized and non synchronized in Java collections?

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.


2 Answers

There are three groups of Collections.

  • Java 1.0 collections which mostly legacy classes. This includes Hashtable, Vector, Stack. These are synchronized but I don't recommend you use them. Properties is perhaps one exception, but I wouldn't use it in a multi-threaded context.
  • Java 1.2 collections added in 1998 which largely replaced these collection are not synchronized, but can be synchronized using Collections.synchronizedXxx() methods
  • Java 5.0 concurrency collections added in 2004 support lock free, thread safe collections.

In short, none of the collections I would recommend you use are synchronized.

like image 58
Peter Lawrey Avatar answered Oct 13 '22 14:10

Peter Lawrey


Thread safe Collections -

  1. ConcurrentHashMap

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.

  1. SynchronizedHashMap

Object level synchronization Both read and writes acquire a lock Locking the collection has a performance drawback May cause contention

  1. Vector

  2. HashTable

  3. CopyOnWriteArrayList

  4. CopyOnWriteArraySet

  5. Stack

Rest all are not thread safe

like image 41
Ujjwal Choudhari Avatar answered Oct 13 '22 13:10

Ujjwal Choudhari