The ConcurrentHashMap class provides a concurrent version of the standard HashMap. So its functionality is similar to a HashMap, except that it has internally maintained concurrency. Depending upon the level of concurrency required the concurrent HashMap is internally divided into segments. If the level of concurrency required is not specified then it is takes 16 as the default value. So internally the ConcurrentHashMap will be divided into 16 segments. Each Segment behaves independently. We will take a look at the segments in the below examples.
Class Hierarchy
java.lang.Object
java.util.AbstractMap<K,V>
java.util.concurrent.ConcurrentHashMap<K,V>
Type Parameters:
K - the type of keys maintained by this map
V - the type of mapped values
All Implemented Interfaces: Serializable, ConcurrentMap<K,V>, Map<K,V>
public ConcurrentHashMap()-
Creates a new, empty map with a default initial capacity (16), load factor (0.75) and concurrencyLevel (16).
Why use Concurrent Hashmap-
We use ConcurrentHashMap when a high level of concurrency is required. But already SynchronizedMap is present so what advantages does ConcurrentHashMap have over synchronized map.Both are thread safe. The major advantage is in case of synchronizedMap every write operation acquires lock on entire SynchronizedMap while in case of ConcurrentHashMap the lock is only on one of the segments.
SynchronizedHashMap | ConcurrentHashMap |
Synchronization is at Object level | Synchronization is at segment level |
A lock is obtained for read/write operation at object level | A lock is obtained for write operation at segment level |
Concurrency level cannot be set for better optimization | Concurrency level can be set for better optimization |
ConcurrentModification Exception is thrown if a thread tries to modify an existing SynchronizedMap which is being iterated | ConcurrentModification Exception is thrown if a thread tries to modify an existing ConcurrentHashMap which is being iterated |
Since at a given time only a single Thread can modify the map and block other threads the performance is comparatively bad. | Multiple Threads can modify ConcurrentHashMap. Hence performance is much better. |
Comments






Leave a Reply