我是靠谱客的博主 甜美战斗机,这篇文章主要介绍对ConcurrentHashMap的remove操作解析,现在分享给大家,希望可以做个参考。

  ConcurrentHashMap的remove源码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
/** * Removes the key (and its corresponding value) from this map. * This method does nothing if the key is not in the map. * * @param key the key that needs to be removed * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt> * @throws NullPointerException if the specified key is null */ public V remove(Object key) { int hash = hash(key.hashCode()); return segmentFor(hash).remove(key, hash, null); }

上面的删除方法:获取该key的hash值,找到所属的桶(如果不知道桶可以去看下ConcurrentHashMap的实现原理),并在桶中执行删除操作

Segment<K,V>重写了这个remove方法,源码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/** * Remove; match on key only if value null, else match both. */ V remove(Object key, int hash, Object value) { lock(); try { int c = count - 1; HashEntry<K,V>[] tab = table; int index = hash & (tab.length - 1); HashEntry<K,V> first = tab[index]; HashEntry<K,V> e = first; while (e != null && (e.hash != hash || !key.equals(e.key))) e = e.next; V oldValue = null; if (e != null) { V v = e.value; if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay // in list, but all preceding ones need to be // cloned. ++modCount; HashEntry<K,V> newFirst = e.next; for (HashEntry<K,V> p = first; p != e; p = p.next) newFirst = new HashEntry<K,V>(p.key, p.hash, newFirst, p.value); tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } }

上面的解析:首先为该桶加锁,通过hash值找到该链在桶中的位置(如果不知道链可以去看下hashMap的实现原理),while循环操作是为了找到需要删除的元素,类似于不断循环,当不是当前hashEntry的时候就next,直接找到.然后判断value==null,,可以看下第一段源码中,传入的参数为null,所以进入if(value==null||value.euqals(v))),在该方法中的HashEntry<K,V> newFirst=e.next.,从新建立该桶下的序列号下的链,当前entry的next为该需要删除元素的下一个元素,并循环原来的真个链,所有不是这个删除元素的都在循环之中,在第一次循环中,假设有1,2,3,4这4个元素,需要删除的为3号元素,第一次循环之后,newFirst中原来的第一个元素为1,next为4,所以第一次循环之后为1,4,第二次循环之后元素到了2,所有2的下一个元素定位1,所以顺序为2,1,4,到了第三个元素,为3时,由于p==e,则跳过,由于p.next没有了,则跳出循环,固重组之后的顺序为2,1,4.关键的代码为:

复制代码
1
2
3
4
HashEntry<K,V> newFirst = e.next; for (HashEntry<K,V> p = first; p != e; p = p.next) newFirst = new HashEntry<K,V>(p.key, p.hash, newFirst, p.value);

 

最后

以上就是甜美战斗机最近收集整理的关于对ConcurrentHashMap的remove操作解析的全部内容,更多相关对ConcurrentHashMap内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部