About NewTechnoBuzz
Contact Us

Friday, July 18, 2014

Difference between Synchronized (Legacy) Collection and Concurrent Collection Classes

Collections classes are heart of Java API. JDK 1.5 introduce some good concurrent collections which is highly efficient for high volume. Every time, a new version of JDK comes, there are new updates in Collection classes of Java API. So, I thought of writing this article what made so much differences between legacy class (synchronized collections) and collection classes.

What is a Synchronized collection?

The synchronized collections (legacy) classes like Hashtable, Vector, and the synchronized wrapper classes, Collections.synchronizedMap and Collections.synchronizedList, are thread safe Collections introduced by earlier Java versions(1.2 thru 1.4). They are implemented as synchronized. So, when one thread is working on an object of legacy class then other thread must have to wait for the before one to release the lock.
Any compound operation needs to be supported with "client side Locking"

However, several factors make them unsuitable for use in highly concurrent applications -- their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationException.

JDK 5 introduced Concurrent collections like ConcurrentHashMap, CopyOnWriteArrayList etc. which are designed for concurrent access from multiple threads which was absent in the synchronized collection as explained above. Instead of synchronizing every method on a common lock, restricting access to a single thread at a time, it uses a finer-grained locking mechanism called lock striping.

For example, ConcurrentHashMap uses an array of 16 locks, each of which guards 1/16 of the hash buckets; bucket N is guarded by lock N mod 16. Assuming the hash function provides reasonable spreading characteristics and keys are accessed uniformly, this should reduce the demand for any given lock by approximately a factor of 16. It is this technique that enables ConcurrentHashMap to support up to 16 concurrent writers.

ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations.
This is all from my side right now. Comments, suggestions and feedbacks are always welcome.