Popular Posts

Saturday, March 28, 2015

Difference Between HashMap, HashTable, Collections.synchronizedMap & ConcurrentHashMap

A brief explanation on how these are internally implemented and work ...

HashMap - plain map implementation, internally implemented as array of (singly) linked-list.

HashTable - synchronized, single-threaded legacy implementation, heavy performance penalty as whole object is locked for any read/write operation.
All its methods are synchronized i.e. the locking is done at the method level and hence the mutex is always at the Hashtable object (this) level.

Collections.synchronizedMap - wrapper implementation, mostly equivalent to hashtable, unlike hashtable - get/put methods are NOT synchronized but uses synchronized blocks. Provides extra constructor with object Mutex as param. Slightly better performance than Hashtable.

The method Collections.synchronizedMap(Map) returns an instance of SynchronizedMap which is an inner class to the Collections class. This class has all its methods in a Synchronized block with a mutex. The difference lies in the mutex here. The inner class SynchronizedMap has two constructors, one which takes only Map as an argument and another which takes a Map and an Object (mutex) as an argument. By default if one uses the first constructor of passing only a Mapthis is used as a mutex. Though, the developer is allowed to pass another object of mutex as a second argument by which the lock on the Map methods would be only on that Object and hence less restrictive than Hashtable.
Hence, Hashtable uses method level synchronization, but Collections.synchronizedMap(Map)provides a flexibility to developer lock on provided mutex with Synchronized block.
ConcurrentHashMap - Very efficient thread-safe / concurrent map implementation. map is divided into sectors (16 default) which can be concurrently accessed and updated in parallel.

No comments: