当前位置: 代码迷 >> 综合 >> ConcurrentHashMap.jdk1.8 put操作:
  详细解决方案

ConcurrentHashMap.jdk1.8 put操作:

热度:72   发布时间:2023-11-23 10:15:59.0

 put操作:

public V put(K key, V value) {return putVal(key, value, false);}/** Implementation for put and putIfAbsent */final V putVal(K key, V value, boolean onlyIfAbsent) {if (key == null || value == null) throw new NullPointerException();int hash = spread(key.hashCode());int binCount = 0;for (Node<K,V>[] tab = table;;) {Node<K,V> f; int n, i, fh;if (tab == null || (n = tab.length) == 0)// 1.初始化数组tab = initTable();// 2.取出key的hash值对应数组位置的节点(如果为null直接new一个节点,否则对该节点添加value)else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {if (casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null)))break;                   // no lock when adding to empty bin}// 3.数组正在扩容,该线程也帮助扩容else if ((fh = f.hash) == MOVED)tab = helpTransfer(tab, f);// 4.对节点添加值else {V oldVal = null;synchronized (f) {if (tabAt(tab, i) == f) {if (fh >= 0) {binCount = 1;// 4.1 链表结构for (Node<K,V> e = f;; ++binCount) {K ek;// 4.1.1在对应位置替换valueif (e.hash == hash &&((ek = e.key) == key ||(ek != null && key.equals(ek)))) {oldVal = e.val;if (!onlyIfAbsent)e.val = value;break;}Node<K,V> pred = e;// 4.1.2直接new nodeif ((e = e.next) == null) {pred.next = new Node<K,V>(hash, key,value, null);break;}}}// 4.2 树形结构else if (f instanceof TreeBin) {Node<K,V> p;binCount = 2;// 4.2.0 转化为树形结构进行putif ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,value)) != null) {oldVal = p.val;if (!onlyIfAbsent)p.val = value;}}}}if (binCount != 0) {if (binCount >= TREEIFY_THRESHOLD)treeifyBin(tab, i);if (oldVal != null)return oldVal;break;}}}addCount(1L, binCount);return null;}