Sunday, March 21, 2021

Java ConcurrentHashMap

Java ConcurrentHashMap

Introduced in Java 1.5, package java.util.concurrent

Implements ConcurrentMap and Serializable interface. HashMap has performance issue in multithreaded application to overcome this issue ConcurrentHashMap introduced. Operations on this thread safe. ConcurrentHashMap does not allow NULL key or NULL value

You can create a object of ConcurrentHashMap like this

ConcurrentHashMap<K, V> obj = new ConcurrentHashMap<K, V>();

This will create a object with initial capacity 16 which is default.

Default capacity 16 : Its default capacity means can store 16 element when object created with default constructor means no initial capacity provided.

Default concurrency level 16 : Default concurrency level 16 means at a time max 16 threads can perform update operation. There is no lock on read operation.

Default load factor 0.75 : When ConcurrentHashMap size reaches 75 % of  total capacity, it resizes the map.

How ConcurrentHashMap handles multithreading ?

It don't apply lock on whole map instead it divide map into segments / buckets and lock each segments so two  separate thread working on separate segment will not block each other. 

By default it create 16 segments and separate lock for each segment.

Lock will only for write and no lock for read operations.

If one thread is iterating over ConcurrentHashMap and other thread is modifying the structure of ConcurrentHashMap then in this case iteartor will not throw ConcuurentModification exception but this will be the case for  HashMap.








Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home