Concurrency-Level: Defines the number which is an estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads.
Load-Factor: It's a threshold, used to control resizing.
Initial Capacity: The implementation performs internal sizing to accommodate these many elements.
A ConcurrentHashMap is divided into number of segments, and the example which I am explaining here used default as 32 on initialization.
A ConcurrentHashMap has internal final class called Segment so we can say that ConcurrentHashMap is internally divided in segments of size 32, so at max 32 threads can work at a time. It means each thread can work on a each segment during high concurrency and atmost 32 threads can operate at max which simply maintains 32 locks to guard each bucket of the ConcurrentHashMap.
As we all know that Map is a kind of data structure which stores data in key-value pair which is array of inner class Entry, see as below:
And ConcurrentHashMap class has an array defined as below of type Entry class:
protected transient Entry[] table;
This Entry array is getting initialized when we are creating an instance of ConcurrentHashMap, even using a default constructor called internally as below:
Here, threshold is getting initialized for re-sizing purpose.
Inserting (Put) Element in ConcurrentHashMap:
Most important thing to understand the put method of ConcurrentHashMap, that how ConcurrentHashMap works when we are adding the element. As we know put method takes two arguments both of type Object as below:
put(Object key, Object value)
So it wil 1st calculate the hash of key as below:
After getting the hashVal we can decide the Segment as below:
Segment seg = segments[(hash & 0x1F)]; // segments is an array defined above
Since it's all about concurrency, we need synchronized block on the above Segment as below:
Size of ConcurrentHashMap
Now when we are asking for size() of the ConcurrentHashMap the size comes out as below:
Getting (get) Element From ConcurrentHashMap
When we are getting an element from ConcurrentHashMap we are simply passing key and hash of key is getting calculated. The defintion goes something like as below:
Note: No need to put any lock when getting the element from ConcurrentHashMap.
Removing Element From ConcurrentHashMap
Now question is how remove works with ConcurrentHashMap, so let us understand it. Remove basically takes one argument 'Key' as an argument or takes two argument 'Key' and 'Value' as below:
Now let us understand how this works internally. The method remove (Object key) internally calls remove (Object key, Object value) where it passed 'null' as a value. Since we are going to remove an element from a Segment, we need a lock on the that Segment.
Hope this will give you a clear understanding of the internal functionality of ConcurrentHashMap.
No comments:
Post a Comment