Difference between Synchronized, Concurrent and Non synchronized Java Collection
As known, java.util.Collection is base interface for java.util.Map, java.util.Set and java.util.List
And all implementations of these interfaces ArrayList, LinkedList, HashSet, TreeSet, HashMap and TreeMap are non synchronized , when used as is.
When a Collection is said to be thread safe?
A Collection is said thread safe, when multiple threads can access, update data in single instance of collection, with out causing corruption/loss of data in that Collection.
How to get synchronized version of List, Set or Map?
Collections utility class provides Concurrent version of each Collection by invoking below methods
Set st = Collections.getSynchronizedSet();
List lst = Collections.getSynchormizedList();
Map mp = Collections.getSynchronizedMap();
Non synchronized collections are not thread safe. Where as, both Synchronized and Concurrent Collections are thread safe.
In addition to above, legacy collections like, Hastable, Vector, Properties are also synchronized.
Though above Collections are thread safe, they are not well suitable for Applications which need to be highly Scalable, and to perform time bound operations. The reason is, synchronization is achieved by making all the public methods of the collection “Synchronized”.
As a solution to this Concurrent Collections have been added during Java. The Concurrent Collection implementations provide much higher concurrency while preserving thread safety.
java.util.concurrent package includes a number of additions to the Java Collections Framework.
ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations.
Implementation of ConcurrentMap is ConcurrentHashMap, which is a concurrent analog of HashMap.
ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches.
An implementation of ConcurrentNavigableMap is ConcurrentSkipListMap, which is a concurrent analog of TreeMap.
Let us see, why synchronized collections cause performance hit, compared to their Concurrent counter parts.
Taking Hashtable and ConcurrentHashMap, as an example. Both of them are thread safe, but consider using them on large number of elements. Hashtable performance would get degraded as the number of elements increase.
But performance of ConcurrentHashMap will not get degraded as the size grows. The reason for this is, underlying implementation of ConcurrentHashMap uses segmentation, i..e it divides entire Collection into multiple segments, and each segment will be locked or unlocked on need basis, so that other threads can simultaneously access other segments which are not locked.