HashMap是一个线程不安全的集合,如果在遍历的过程中同时对该集合进行修改操作,例如put,add,remove等,
会抛出java.util.ConcurrentModificationException异常,那么究竟这个异常为何抛出,下面从源码层面来分析一下。
跟踪代码:

 查看HashMap源码,具体抛该异常的地方为:

final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}

  如果HashMap中modCount和expectedModCount不相等,则会抛出异常

查看modCount:

  具体用途是记录该HashMap修改次数,比如在对一个HashMap put操作时,会对modCount进行++modCount操作(红色标注的地方)

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

  而在remove操作的时候,也会对modCount进行同样的操作:

final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
查看expectedModCount:

  它是HashIterator中的一个变量,在对HashMap迭代的时候,将modCount赋给expectedModCount,具体代码:

HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
何时调用HashIterator():

  查看HashMap entrySet()源码:

public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es;
return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}

  此处新建一个EntrySet对象,而在对EntrySet进行迭代的时候,会调用:

public final Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}

  新建一个EntryIterator对象,查看该类描述:

final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}

  它继承HashIterator,因此在new EntryIterator()的时候会默认调用它父类HashIterator的无参构造方法。

总结:

  HashMap迭代遍历的时候,会初始化expectedModCount=modCount,这时候对HashMap进行修改操作,modCount会+1,继续遍历的时候expectedModCount!=modCount,继而抛出java.util.ConcurrentModificationException异常。

最新文章

  1. HashMap两种遍历方式的深入研究
  2. MySQL 升级详细步骤 (包括 Percona)
  3. redis常用命令、常见错误、配置技巧等分享
  4. AngularJS学习--- AngularJS中的模板template和迭代器过滤filter step2 step3
  5. js 格式验证总结
  6. C# 生成简单验证码
  7. C# CRC32
  8. Android 如何添加一种锁屏方式
  9. nginx图片服务器配置
  10. Bootstrap_排版_文字样式
  11. linux查询进程号,出现两个进程
  12. 为了异常安全(swap,share_ptr)——Effecive C++
  13. Problem 4: Largest palindrome product
  14. ORA-00600: internal error code, arguments: [2662]
  15. qtp10 安装笔记
  16. itexpdf同一个段落不同文字,如何设置不同的格式
  17. Java 之递归遍历目录
  18. vscode使用wsl调试代码
  19. ACtiveMQ中间件-消息的接收和发送
  20. SET操作符

热门文章

  1. SQL SERVER中LIKE在Char和nChar输出结果不一致解惑
  2. x64 assembler fun-facts(转载)
  3. youtube-dl 安装和用法
  4. GPU、CPU、FPGA
  5. day14_雷神_前端02
  6. uniGUI日志的控制
  7. Ocelot使用
  8. C++中const关键字 理解
  9. Win32 CMD批处理命令
  10. 使用 PLSQL 连接 Oracle9i 数据库