PS. All sources of this article are based on jdk1.6
First of all, Concurrenthashmap is not a complete replacement for Hashtable, because the Concurrenthashmap get, clear function is weakly consistent (and later), and Hashtable is strong consistent. The authors explain this: we put the contrast between "consistency strength" and "extensibility" on the user's balance, so most collections offer two versions of synchronized and concurrent. However, the real need for "strong consistency" scenario may be very small, most of our applications Concurrenthashmap is satisfied. data structure of Concurrenthashmap
Have to say, concurrenthashmap design is quite ingenious, it has several segments, each section below is a Hashtable (similar), so each segment has a lock (distributed lock), each segment of the lock between each other, can achieve concurrent operation. Words not much to say, on the code.
Final segment<k,v>[] segments;
You can see that Concurrenthashmap is actually a segment array, so what is segment?
Static final class Segment<k,v> extends Reentrantlock implements Serializable {
...
Transient volatile hashentry<k,v>[] table; Found segment is actually a hashentry array
...
}
What about the Hashentry?
Static Final class Hashentry<k,v> {
final K key;
final int hash;
volatile V value;
Final hashentry<k,v> next;
...
}
Hashentry is a single linked list
So Concurrenthashmap's data structure is as follows:
Each of these segment points to the data structure, in fact, is a hashtable, so that each segment have a separate lock, to ensure that when access to different segment not affect each other. the basic method of Concurrenthashmap
The basic methods are divided into several categories:
1, Denega Lock: Put,putifabsent,remove,replace, etc.
2, without locking: Get,containskey, etc.
3, the entire data structure of the lock: Size,containsvalue, such as constructors
Public concurrenthashmap (int initialcapacity,float loadfactor, int concurrencylevel) {if (!) ( Loadfactor > 0) | | Initialcapacity < 0 | | Concurrencylevel <= 0) throw new IllegalArgumentException ();
Parameter validity check if (Concurrencylevel > max_segments) concurrencylevel = max_segments; For example, I entered the concurrencylevel=12, then Sshift = 4,ssize = 16, so sshift is meant to be 1 left moved several times than the Concurrencylevel big,
Ssize is the number int sshift = 0 of the power exponent of the least 2, which is greater than or equal to concurrencylevel;
int ssize = 1;
while (Ssize < concurrencylevel) {++sshift; Ssize <<= 1;
Ssize = ssize << 1, ssize = ssize * 2} segmentshift = 32-sshift; Segmentmask = ssize-1; The binary of Segmentmask is a number this.segments = Segment.newarray (ssize) with a total of 1; The number of segment is Ssize, which is the number of yellow squares above, the default 16 if (Initialcapacity > maximum_capacity) initialcapacity = Maximum_capaci
TY;
int c = initialcapacity/ssize;
if (c * ssize < initialcapacity) ++c;
int cap = 1; WHile (Cap < c) Cap <<= 1; for (int i = 0; i < this.segments.length ++i) this.segments[i] = new segment<k,v> (cap, loadfactor);
The number of green blocks is the cap, which is a power exponent of 2, and the default is 1, which is a table array of cap size constructed under each Segment Segment (int initialcapacity, float lf) {loadfactor = LF; Settable (Hashentry.<k,v>newarray (initialcapacity));//constructed a initialcapacity size table} put function
Public V-Put (K key, V value) {if (value = = null) throw new NullPointerException ();//Explicitly specify value cannot be null int
hash = hash (Key.hashcode ()); return Segmentfor (hash). Put (key, hash, value, false); Segmentfor below, locate the Segment subscript, then put the final segment<k,v> segmentfor (int hash) {//Look for Segment's subscript return seg ments[(hash >>> segmentshift) & Segmentmask];
Said the Segmentmask is a 2 into the total is 1 of the number, then the &segmentmask to ensure that the subscript is less than equal to Segmentmask, and HashMap of the search for subscript similar. //Real put Operation V put (K key, int hash, V value, Boolean onlyifabsent) {lock ();
Lock first, you can see, put operation is in the segment inside lock, that is, each segment can add a lock try {int c = count; if (c + + > Threshold)//ensure capacity rehash (); Judging capacity, if not enough on the expansion hashentry<k,v>[] tab = table; Assign a table to a local variable tab, because the table is a volatile variable, the cost of reading and writing volatile variable is very high, the compiler can not do any optimization to the volatile variable's read and write, direct multiple access to a non-volatile instance variable has little impact
, the compiler will do the appropriate optimizations. int index = hash & (tab.length-1); Looking for the subscript hashentry&l of a tableT
K,v>-Tab[index];
Hashentry<k,v> e = A; while (e!= null && (e.hash!= Hash | |!key.equals (E.KEY))) e = E.next;
Traverse the single linked list, find the key the same, if not found, E point to the chain of the tail V oldValue;
if (e!= null) {//If there is the same key, then replace OldValue = E.value directly;
if (!onlyifabsent) E.value = value;
else {//Otherwise insert a new node in the list header oldValue = null;
++modcount;
Tab[index] = new hashentry<k,v> (key, hash, a, value); Count = C;
Write-volatile} return oldValue;
finally {unlock (); }
}
This method is also in the case of holding a section lock, the first to determine whether the need for rehash, need to first rehash, expansion is aimed at a single segment, that is, a single segment of the number of data than the set amount of time will trigger expansion. The next is to find if there is a node of the same key, and if so, replace the value of the node directly. Otherwise create a new node and add it to the header of the hash chain, then be sure to modify the value of Modcount and count, and also modify the value of count to be in the last step. Put method calls the Rehash method, Reash method is also very sophisticated, mainly using the size of the table for 2^n, and hashmap expansion of the basic same, here is not introduced.
There is also a function called putifabsent (K key, V value), which is almost exactly the same as put, and, if this key is not present in the map, insert the data, if there is this key, then do not overwrite the original value, which is not inserted. Remove function
The >remove operation is also given to the remove in paragraph, as follows: V remove (object key, int hash, object value) {lock ();
A lock try {int c = count-1 is first obtained in the paragraph;
hashentry<k,v>[] tab = table;
int index = hash & (tab.length-1);
Hashentry<k,v>-Tab[index];
Hashentry<k,v> e = A;
while (e!= null && (e.hash!= Hash | |!key.equals (E.KEY))) e = E.next;
V oldValue = null;
if (e!= null) {//if the key v = e.value is found;
if (value = null | | value.equals (v)) {oldValue = v;
All entries following removed node can stay/In list, but all preceding ones
Cloned.
++modcount; hashentry<k,v> Newfirst = E.next; Newfirst at this point for the next for the node to delete (hashentry<k,v> p = A-P!= e; p = p.next) Newfi rst = new Hashentry<k,v> (P.KEY,P.HASH,NEWFIrst, P.value)//From the beginning of the chain list to delete the node before all nodes are copied into the Newfirst, the following figure tab[index] = Newfirst; Count = C;
Write-volatile}} return oldValue;
finally {unlock (); }
}
Why remove it in such a way that a careful classmate will find that the key and next of the Hashentry defined above are final, so you can't change the point of next, so you copy another point pointing to the deleted node. Get function
Public V get (Object key) {int hash = hash (Key.hashcode ()); The double hash, like HashMap, is also for better discretization return Segmentfor (hash). Get (key, hash); First look for Segment subscript, and then get} final segment<k,v> segmentfor (int hash) {//Find Segment subscript return segments[(hash &G T;>> segmentshift) & Segmentmask];
Said the Segmentmask is a 2 into the total is 1 of the number, then the &segmentmask to ensure that the subscript is less than equal to Segmentmask, and HashMap of the search for subscript similar. } V get (Object key, int hash) {//count is a volatile variable, count is very clever, the last step after each put and remove to update count, is to get when the compiler does not reorder the code, to guarantee if (count!= 0) {hashentry<k,v> e = GetFirst (hash);
Look for the subscript for the table, which is the table header while (e!= null) {if (E.hash = hash && key.equals (E.key)) {
V v = e.value;
if (v!= null) return V; Return Readvalueunderlock (e);
Recheck Lock read, this lock reading does not need to recalculate position, but directly to get e value} e = E.next;
} return null; } hashentry<k,v> getfirst (int hash) {Hashentry<k,v>[] tab = table;
Return Tab[hash & (tab.length-1)]; }
Read the above code I have a question, that is, if the key to find the corresponding value is NULL, lock and read again, since the above put operation does not allow value is null, then the read value of why there is null situation. We analyze this situation, where the put and get operations can be divided into two situations:
1, put key already exists, because the value is not final, can be directly updated, and value is volatile, so the modification will be immediately visible to the get thread, and not wait until the put method ends.
2, put the key does not exist, then will be inserted in the list table header a data, then the new hashentry assignment to Tab[index] can immediately be visible to the thread executing get, we know that every time we put the end to update a count variable (write), And every time you get the data, you read a count variable (read) at the very beginning, and you find that count is volatile, and for the same volatile variable, there is a volatile write happens-before volatile read, So if the write occurs before reading, then the new hashentry assignment to Tab[index] is visible to the get thread, but it is not possible to guarantee that the new Hashentry is assigned to Tab[index if the write does not occur before reading. GetFirst (hash) before the Get function, that is, if put in a segment instance adds a entry to the table, another thread executes the get in the same segment instance before the count assignment operation. To get the value of this newly added entry, then it is possible to not get it, which is the weak consistency of getting. But when will the key be found but the value read is NULL, take a closer look at the statement of the put operation: tab[index] = new Hashentry (key, hash, first, value), in this statement, The assignment of value in the Hashentry constructor and the assignment of Tab[index] may be reordered, for example, it is possible for this statement to perform a value assignment on a key, then perform an assignment to Tab[index, and finally assign a value to A GET is a null value if you assign a value to the tab and key, but the value has not yet been assigned.
Can look at this article in detail: http://ifeve.com/concurrenthashmap-weakly-consistent/
This means that a lock-free get operation is a weakly consistent operation.Clear function
public void Clear () {
for (int i = 0; i < segments.length ++i) //loop clear out the contents of each segment
segments[i].clear ();
}
void Clear () {
if (count!= 0) {
lock (); Denega Lock
try {
hashentry<k,v>[] tab = table;
for (int i = 0; i < tab.length i++)
tab[i] = null;
++modcount;
Count = 0; Write-volatile
} finally {
unlock ();
}
}
}
Because there is no global lock, after clearing a segments, cleaning the next segments, the segments may be added to the data, so when clear returns, the Concurrenthashmap is likely to have data. Therefore, the clear method is weakly consistent. size function
public int size () {final segment<k,v>[] segments = this.segments;
Long sum = 0;
Long check = 0;
Int[] mc = new Int[segments.length]; Try a few times to get accurate count.
On failure due to//continuous async changes into table, resort to locking.
for (int k = 0; k < Retries_before_lock; ++k) {check = 0;
sum = 0;
int mcsum = 0; for (int i = 0; i < segments.length ++i) {sum + = Segments[i].count; The number of data in each segment is Mcsum + + = mc[i] = Segments[i].modcount; Loops Add Modcount} if (mcsum!= 0) {//If 0, representing no data changes at all, that is, the size is 0 for t i = 0; i < segments.length; ++i) {check + = Segments[i].count; Again, the number of data in each segment is recycled, why do you do this again, and then say if (Mc[i]!= segments[i].modcount) {check =-1 ;
Force retry//If Modcount is inconsistent with previous statistics, check directly assigns a value-1, again to break; }} if (check = = sum) break;
} if (check!= sum) {//Resort to locking all segments sum = 0;
for (int i = 0; i < segments.length ++i)//loop fetch all segment lock Segments[i].lock ();
for (int i = 0; i < segments.length ++i)/////-add sum of Count + = Segments[i].count When holding all segment locks;
for (int i = 0; i < segments.length; ++i)//cyclic release of all segments of the lock Segments[i].unlock ();
if (Sum > Integer.max_value)//return return integer.max_value;
else return (int) sum; }
If we want to count the size of the elements in the entire concurrenthashmap, we must count the size of all the segment elements and sum them. The global variable count in segment is a volatile variable, so in a multithreaded scenario, do we add all the segment count directly to get the entire concurrenthashmap size? No, although the addition can get the most recent value of the count of each segment, but the count that can be used before adding a change, then the statistical results are not allowed. So the safest thing to do is to lock all the segment Put,remove and clean methods when you're counting size, but it's obviously very inefficient because the odds of a previous cumulative count changing during the count operation are very small, So Concurrenthashmap's approach is to first try 2 times by not locking the segment of the way to statistics each segment size, if the statistical process, the container count has changed, then the way to add a lock to count the size of all segment. So how does concurrenthashmap determine if the container has changed in the statistics? Using the Modcount variable, the variable modcount is added to 1 before the put, remove, and clear methods are used, so that the size of the container is changed before and after the size of the statistic. The implementation of size () also needs to be noted that you must first segments[i].count to Segments[i].modcount, because Segment[i].count is the access to volatile variables, and then segments [I].modcount can get almost the most recent values, here and the way getting method is the same, but also a volatile write happens-before volatile read the problem.
Above 18 lines of code, throws a question, is why calculates again, above said only needs to compare modcount not to be possible. But with a careful analysis, you'll find that in 13 lines of 14 lines of code, after the count is calculated, the value of the possible count before the calculation of Modcount is changed again, and then the 18-line code is mostly about solving the problem. containsvalue function
The
ContainsKey function is simpler and is a simple get without locking, and here's an interesting place to say Containsvalue
public boolean Containsvalue (Object value) {if (value = = null) throw new NullPointerException ();
Explanation of Modcount use above final segment<k,v>[] segments = this.segments;
Int[] mc = new Int[segments.length];
Try a few times without locking for (int k = 0; k < Retries_before_lock; ++k) {int sum = 0;
int mcsum = 0; for (int i = 0; i < segments.length; ++i) {int c = Segments[i].count;
Notice this line, declare a C variable, and assign a value, but the following is completely useless.
Mcsum + = Mc[i] = Segments[i].modcount;
if (Segments[i].containsvalue (value)) return true; Boolean cleansweep = true; Default structure does not change if (mcsum!= 0) {for (int i = 0; i < segments.length; ++i) {int c = SEGM
Ents[i].count;
if (Mc[i]!= segments[i].modcount) {//If the structure has changed, CleanSweep = False CleanSweep = false;
Break }} if (CleanSweep)//If not changed, return false directly;
}//Resort to locking all segments for (int i = 0; i < segments.length; ++i) Segments[i].lock ();
Boolean found = false;
try {for (int i = 0; i < segments.length; ++i) {if (Segments[i].containsvalue (value)) {
Found = true;
Break
finally {for (int i = 0; i < segments.length ++i) Segments[i].unlock ();
return found; }
Note that the above code 15 lines, which have the statement int c = Segments[i].count; But C has never been used, even so, the compiler can not do optimization to remove this statement, because there is a reading of the volatile variable count, the only purpose of this statement is to ensure that Segments[i].modcount read the most recent values, It says the question.
This article refers to the article:
1, http://ifeve.com/concurrenthashmap-weakly-consistent/
2, http://www.iteye.com/topic/344876