In-depth concurrenthashmap one, has introduced the basic structure of concurrenthashmap, segment composition, hashentry composition as well as the creation of Concurrenthashmap included.
This article focuses on the case of putting elements into Concurrenthashmap, that is, the put (K key,v value) method.
Concurrenthashmap put into a key,value the simplified steps are as follows:
1. Take the hash value of key to calculate the subscript of the segment array in the storage.
2. After locating the segment array subscript, remove the segment, and then calculate the array subscript that needs to be stored in the segment Hashentry
3. Finally put the key,value into
Detailed steps as shown:
Then analyze the source code. The first is to get the source of the segment to hold the element, the code is as follows:
Public V put (K key, V value) {
segment<k,v> s;
if (value = = null)
throw new NullPointerException ();
int hash = hash (key);
Int J = (hash >>> segmentshift) & Segmentmask;
if ((s = (segment<k,v>) unsafe.getobject //nonvolatile; recheck
(segments, (J << Sshift) + sbase) = = NULL)//in ensuresegment
s = ensuresegment (j);
Return S.put (key, hash, value, false);
}
Here first will calculate the hash value of key, hash (key) method will try to break the hash, reduce the hash conflict.
After calculating the hash, the statement int j = (hash >>> segmentshift) & Segmentmask is used; To get the segment array subscript.
Then use Unsafe.getobject to try to get segment from the segment array. If NULL then the Ensuresegment (j) method is called to create one and the CAS is set to the segment array.
Since the segment is only created and placed in the segment array when the first one does not exist, it is only in this step that the competition with other threads will occur.
Therefore, for the creation of segment and into the segment array, Concurrenthashmap uses CAS operations to atomically put segment. This also conforms to small or
A moderate concurrency scenario is appropriate for CAS operations.
With segment, call segment's Put method to insert the element into the corresponding hashentry array. Segment's Put method source code is as follows:
Final V put (K key, int hash, V value, Boolean onlyifabsent) {hashentry<k,v> node = trylock ()? NULL:
Scanandlockforput (key, hash, value);
V OldValue;
try {hashentry<k,v>[] tab = table;
int index = (tab.length-1) & hash;
hashentry<k,v> first = Entryat (tab, index); for (hashentry<k,v> e = first;;)
{if (E! = null) {k k;
if (k = e.key) = = Key | | (E.hash = = Hash && key.equals (k)))
{oldValue = E.value;
if (!onlyifabsent) {e.value = value;
++modcount;
} break;
} e = E.next; } else {if (node! = null) Node.setnext (first);
else node = new Hashentry<k,v> (hash, key, value, first);
int c = count + 1;
if (C > Threshold && tab.length < maximum_capacity) rehash (node);
else Setentryat (tab, Index, node);
++modcount;
Count = C;
OldValue = null;
Break
}}} finally {unlock ();
} return oldValue; }
This is partly because of the put operation for each segment, which is relatively competitive. Therefore, lock is used to control the synchronization.
The following steps are carried out:
1. This will first call Reentrantlock's Trylock method to see if the lock can be acquired. can go to the 3rd step. Otherwise, enter the 2nd step and call Scanandlockforput to get the lock.
2. Call the Scanandlockforput method to try to obtain a CAS acquisition lock. When you enter this method, you try to get it once, and if you get it, it returns immediately. Otherwise, the CAS acquires the lock multiple times,
In the process of acquiring a lock, if the element to be placed does not exist in the Hashentry array, create one first.
The source code is as follows:
Private hashentry<k,v> Scanandlockforput (K key, int hash, V value) {hashentry<k,v> first = Entryf
Orhash (this, hash);
hashentry<k,v> e = first;
hashentry<k,v> node = null; int retries =-1; Negative while locating node while (!trylock ()) {hashentry<k,v> F;//to Recheck Fir St below if (retries < 0) {if (E = = null) {if (node = = Nu
ll)//speculatively Create node node = new Hashentry<k,v> (hash, key, value, NULL);
retries = 0;
} else if (Key.equals (e.key)) retries = 0;
else E = E.next;
} else if (++retries > Max_scan_retries) {lock ();
Break } else if ((retries & 1) = = 0 && (f = entryforhash (this, hash))! = first) { E = first = f;
Re-traverse if entry changed retries =-1;
}} return node; }
You can see that once the number of retries is more than max_scan_retries (here is 64 times) the lock method of the Reentrantlock is called to block the acquisition lock (in the lock method or the CAs gets the lock, if you still cannot get the
This thread is put into the CLH queue and finally blocked, detailed in depth concurrency Aqs II).
What's interesting is the last one.
else if ((retries & 1) = = 0 &&
(f = entryforhash (this, hash))! = first)
This part of the code, which determines if the current hashentry to store the first node of the location, if there are other threads have completed the operation of the insert, then the retries will be set to 1.
Concurrenthashmap that the lock will be acquired soon after this situation.
Always repeat the CAs to get the lock and get to the back node.
3. Once you have acquired the lock, you can put the element into the hashentry.
Here are two things:
One is that the key element exists at the corresponding position of the current Hashentry array, and the value of the current hashentry is replaced by the new value.
One is that the key element does not exist at the corresponding position of the current Hashentry array, and the element is inserted at the appropriate position.
For the first case of the source code in the above put method, part of the fragment is as follows:
try {hashentry<k,v>[] tab = table;
int index = (tab.length-1) & hash;
hashentry<k,v> first = Entryat (tab, index); for (hashentry<k,v> e = first;;) { if (E! = null) {//here if E is not empty, then the current hashentry position is already an element, then traverse the conflict chain to see if the current key is already
Presence in Hashentry k K;
if (k = e.key) = = Key | | (E.hash = = Hash && key.equals (k)))
{//There is currently a key element, then replace it oldValue = E.value;
if (!onlyifabsent) {e.value = value;
++modcount;
} break;
} e = E.next; } else {//This branch considers the current position Hashentry no element exists or does not currently exist with the same key hashentrY. At this point, if the previous scanandlockforput has returned the created Hashentry node, direct the next pointer of the new node node to the first node of the hashentry position if (node! =
NULL) Node.setnext (first); Else //node creates a new hashentry for storing key,value node = new Hashentry<k,v
> (hash, key, value, first);
int c = count + 1;
if (C > Threshold && tab.length < maximum_capacity) rehash (node);
else Setentryat (tab, Index, node);
++modcount;
Count = C;
OldValue = null;
Break
}}} finally {unlock (); }
You can see that there is an optimization part called
Scanandlockforput
method, when CAs tries to acquire a lock, if there are no elements in the current Hashentry array position to hold the element, it is considered less competitive, so it is speculative to create a node to hold the Key,value.
Otherwise, because it is not certain that a new node should be created, because it is possible that the key value already exists, it is actually only necessary to update it. There are, of course, factors that argue that competition is more intense.