ConcurrentHashMap Analysis Based on JDK1.8, concurrenthashmap
I have read the analysis of ConcurrentHashMap before, and I feel like I know more about it. But I received an interview last night and asked me to explain all the ConcurrentHashMap I knew.
Then I am stuttering, and I should be able to analyze it without any accident. Today, I am determined to analyze this omnipotent package, ConcurrentHashMap
Analyze ConcurrentHashMap in several aspects:
- Put Method
- Remove Method
- Get Method
(1) put Method
1 public V put(K key, V value) {2 return putVal(key, value, false);3 }
The putVal method is called and three parameters are passed in. The first is key, the second is val, and the third is onlyIfAbsent (meaning: if true, if the inserted key is the same, the val value is not replaced. The default value is false, replace the latest val value)
There are many putVal methods. Let's talk about them in two parts:
1 // Part 2 final V putVal (K key, V value, boolean onlyIfAbsent) {3 // determine the validity of input parameters. 4 if (key = null | value = null) throw new NullPointerException (); 5 // hash value 6 int hash = spread (key. hashCode (); 7 int binCount = 0; 8 for (Node <K, V> [] tab = table;) {9 Node <K, V> f; int n, I, fh; 10 // if the hash table has not been initialized, initialize it 11 if (tab = null | (n = tab. length) = 0) 12 tab = initTable (); 13 // locate the index position of the hash Array Based on the hash value of the key. 14 // if it is null, then add a node 15 else if (f = tabAt (tab, I = (n-1) & hash) = null) to the location in CAS lockless mode) {16 if (casTabAt (tab, I, null, 17 new Node <K, V> (hash, key, value, null) 18 break; 19}
In the fourth row, if both the key and val values are null, an exception is thrown directly. Therefore, neither key nor val can be null.
The second note is to hash this function.
1 static final int spread(int h) {2 return (h ^ (h >>> 16)) & HASH_BITS;3 }
I have introduced it in HashMap. I will not elaborate on it. It is very important.
The third note is to initialize the initTable function.
1 private final Node <K, V> [] initTable () {2 Node <K, V> [] tab; int SC; 3 // Initialization is performed if the table is empty. 4 while (tab = table) = null | tab. length = 0) {5 // if sizeCtl is smaller than zero, it indicates that a thread is initializing. 6 // The current thread should discard CPU usage. 7 if (SC = sizeCtl) <0) 8 Thread. yield (); // lost initialization race; just spin 9 // otherwise it indicates that no thread has initialized the table, so this thread will do this work 10 else if (U. compareAndSwapInt (this, SIZECTL, SC,-1) {11 // For the sake of insurance, Judge again whether the following table is empty 12 try {13 if ((Tab = table) = null | tab. length = 0) {14 // if SC is greater than zero, the capacity has been initialized. Otherwise, the default capacity is 15 int n = (SC> 0 )? SC: DEFAULT_CAPACITY; 16 @ SuppressWarnings ("unchecked") 17 // array built based on capacity 18 Node <K, V> [] nt = (Node <K, V> []) new Node <?,?> [N]; 19 table = tab = nt; 20 // calculate the threshold, equivalent to n * 0.7521 SC = n-(n >>> 2 ); 22} 23} finally {24 // set the threshold value 25 sizeCtl = SC; 26} 27 break; 28} 29} 30 return tab; 31}
We can see lines 7 and 8. If a thread is initializing, wait and let out the cpu.
Initialization only allows one thread to initialize the table. If other threads come in, other threads will be handed over the CPU to wait for the next system scheduling. This ensures that the table is initialized by only one thread at the same time.
The default value is 16 for initialization, and the period value is 0.75.
Let's go back to the putVal method.
1 // The bucket node is detected to be of the ForwardingNode type, assisting in expansion of 2 else if (fh = f. hash) = MOVED) 3 tab = helpTransfer (tab, f); 4 // The bucket node is a common node, lock the bucket header node and try to add a node 5 else {6 V oldVal = null; 7 synchronized (f) {8 if (tabAt (tab, I) to the end of the linked list) = f) {9 // Add elements to a common linked list. Do not repeat 10 if (fh> = 0) {11 binCount = 1; 12 for (Node <K, v> e = f; ++ binCount) {13 K ek; 14 if (e. hash = hash & (ek = e. key) = key | (ek! = Null & key. equals (ek) {15 oldVal = e. val; 16 if (! OnlyIfAbsent) 17 e. val = value; 18 break; 19} 20 Node <K, V> pred = e; 21 if (e = e. next) = null) {22 pred. next = new Node <K, V> (hash, key, value, null); 23 break; 24} 25} 26} 27 // add elements to the red/black tree, the hash value of the TreeBin Node is TREEBIN (-2) 28 else if (f instanceof TreeBin) {29 Node <K, V> p; 30 binCount = 2; 31 if (p = (TreeBin <K, V>) f ). putTreeVal (hash, key, value ))! = Null) {32 oldVal = p. val; 33 if (! OnlyIfAbsent) 34 p. val = value; 35} 36} 37} 38} 39 // binCount! = 0 indicates that a node is successfully added or modified to the linked list or the red/black tree. 40 // binCount = 0 indicates that the put Operation adds a new node to the first node of a bucket. 41 if (binCount! = 0) {42 // The chain table depth exceeds 8 to the red/black tree 43 if (binCount> = TREEIFY_THRESHOLD) 44 treeifyBin (tab, I); 45 // oldVal! = Null indicates that this operation is to modify operation 46 // directly return the old value. You do not need to perform the following expansion boundary check 47 if (oldVal! = Null) 48 return oldVal; 49 break; 50} 51} 52} 53 // update baseCount in CAS mode, and determine whether to expand 54 addCount (1L, binCount ); 55 // This step indicates that this put operation is an add operation, otherwise 56 return null is returned long ago;
We can see the third line. If the hash of f is MOVED, it will help him resize (it indicates that at least one thread is resizing)
To tell the truth, I don't quite understand this method. I checked some information on the Internet:
First, each thread receives its own job range first, and then starts -- I to traverse its job range and process each bucket. If the header node of the bucket is empty, use ForwardingNode to identify that the bucket has been processed. If a bucket has been processed, skip the next bucket. If the bucket is normal, lock the first node of the bucket and perform normal migration. After the migration is complete, the Location Identification Position of the original table will still be processed.
When I <0, it indicates that the processing speed of this thread is fast enough, and the last part of the entire table has been processed by it, now you need to check whether there are other threads still migrating in their own segments.
The code after putVal is clear. If it is a linked list, find the end node and insert it. If it is a red/black tree, insert the nursery rhyme.
So far, the source code analysis of the put method has completely ended, and it feels really complicated. At this point, I feel that I have not fully understood what each line of code means.
(2) remove Method
1 public V remove(Object key) {2 return replaceNode(key, null, null);3 }
Three parameters: the first parameter is the key, and the second parameter is the val parameter. The deletion parameter is directly set to null for gc to recycle. The third is the Object cv. The meaning is not clear yet. Let's continue.
There are two parts:
1 // Part 2 final V replaceNode (Object key, V value, Object cv) {3 // first find the key location hash 4 int hash = spread (key. hashCode (); 5 for (Node <K, V> [] tab = table;) {6 Node <K, V> f; int n, I, fh; 7 // if the table is empty, null 8 if (tab = null | (n = tab. length) = 0 | 9 (f = tabAt (tab, I = (n-1) & hash) = null) 10 break; 11 // if there is a resizing thread, help him resize 12 else if (fh = f. hash) = MOVED) 13 tab = helpTransfer (tab, f );
First, traverse the bucket node of the entire table. If the table is not initialized or cannot be located based on the hash value of the parameter, null is returned.
If the located bucket node type is ForwardingNode, call helpTransfer to help resize.
1 else { 2 V oldVal = null; 3 boolean validated = false; 4 synchronized (f) { 5 if (tabAt(tab, i) == f) { 6 if (fh >= 0) { 7 validated = true; 8 for (Node<K,V> e = f, pred = null;;) { 9 K ek;10 if (e.hash == hash &&11 ((ek = e.key) == key ||12 (ek != null && key.equals(ek)))) {13 V ev = e.val;14 if (cv == null || cv == ev ||15 (ev != null && cv.equals(ev))) {16 oldVal = ev;17 if (value != null)18 e.val = value;19 else if (pred != null)20 pred.next = e.next;21 else22 setTabAt(tab, i, e.next);23 }24 break;25 }26 pred = e;27 if ((e = e.next) == null)28 break;29 }30 }31 else if (f instanceof TreeBin) {32 validated = true;33 TreeBin<K,V> t = (TreeBin<K,V>)f;34 TreeNode<K,V> r, p;35 if ((r = t.root) != null &&36 (p = r.findTreeNode(hash, key, null)) != null) {37 V pv = p.val;38 if (cv == null || cv == pv ||39 (pv != null && cv.equals(pv))) {40 oldVal = pv;41 if (value != null)42 p.val = value;43 else if (t.removeTreeNode(p))44 setTabAt(tab, i, untreeify(t.first));45 }46 }47 }48 }49 }50 if (validated) {51 if (oldVal != null) {52 if (value == null)53 addCount(-1L, -1);54 return oldVal;55 }56 break;57 }58 }
There are a lot of code, but I think it is not difficult to think about it. The lock is directly applied after the bucket is found. Determine whether it is a linked list or a tree, and then delete it.
(3) get Method
1 public V get(Object key) { 2 Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek; 3 int h = spread(key.hashCode()); 4 if ((tab = table) != null && (n = tab.length) > 0 && 5 (e = tabAt(tab, (n - 1) & h)) != null) { 6 if ((eh = e.hash) == h) { 7 if ((ek = e.key) == key || (ek != null && key.equals(ek))) 8 return e.val; 9 }10 else if (eh < 0)11 return (p = e.find(h, key)) != null ? p.val : null;12 while ((e = e.next) != null) {13 if (e.hash == h &&14 ((ek = e.key) == key || (ek != null && key.equals(ek))))15 return e.val;16 }17 }18 return null;19 }
Similar to the get method of HashMap. No concurrent operations are involved. Get the hash value of the key directly. If it is the first node, return directly. Otherwise, while loop search