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.
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.
0 comments