Wednesday, 22 March 2017

Synchronized vs Concurrent Collections

Synchronize means: the resource (which is synchronized) can't be modified by multiple threads simultaneously.

Synchronized and Concurrent Collections can be used to provide thread-safety; however differences between them come in performance, scalability and the way to achieve thread-safety. Synchronized collections (=synchronized HashMap, Hashtable, HashSet, Vector and synchronized ArrayList) are much slower than their concurrent counterparts (=ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet). Because synchronized collections locks the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List. They achieve thread safety by using advanced and sophisticated techniques like lock stripping.

Hashtable vs. ConcurrentHashMap
So what is the difference between Hashtable and ConcurrentHashMap, both can be used in multi-threaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration. Since ConcurrentHashMap introduced concept of segmentation, It doesn't matter whether how large it becomes because only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locks certain portion of Map while Hashtable lock full map while doing iteration or performing any write operation.

ArrayList vs. CopyOnWriteArrayList

CopyOnWriteArrayList allows multiple reader threads to read without synchronization and when a write happens it copies the whole ArrayList and swap with a newer one.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...