2019独角兽企业重金招聘Python工程师标准>>>
public class _01_普通map的错误 {
public static void useMap(final Map scores) {
scores.put("WU",19);
scores.put("zhang",14);
try {
for(final String key : scores.keySet()) {
System.out.println(key + ":" + scores.get(key));
scores.put("liu",12);
}
}catch (Exception ex) {
System.out.println("traverse key fail:" + ex);
}
try {
for (final Integer value : scores.values()) {
scores.put("liu", 13);
// scores.put("zhao", 13);
System.out.println(value);
}
}catch (Exception ex){
System.out.println("traverse value fail:" + ex);
}
}
public static void main(String[] args) {
System.out.println("Using Plain vanilla HashMap");
useMap(new HashMap());
System.out.println("Using synchronized HashMap"); //不能在迭代遍历的同时,对map做更新
useMap(Collections.synchronizedMap(new HashMap()));
System.out.println("Using concurrent HashMap"); //能够更新
useMap(new ConcurrentHashMap());
}
}
结果:
HashMap会抛出java.util.ConcurrentModificationException异常;ConcurrentHashMap会正常执行。
为什么HashMap会抛出异常?
HashMap的 keySet(), values(), 都使用的强一致性迭代器,每一次获取节点元素,都要检查map的操作次数。
public Set keySet() {
Set ks;
// 1 调用HashMap的keySet()函数,会生成一个KeySet()对象
return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
}
final class KeySet extends AbstractSet {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
//2 遍历时,生成KeySet的迭代器KeyIterator
public final Iterator iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer super K> action) {
Node[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
final class KeyIterator extends HashIterator
implements Iterator {
//3. 遍历,获取下一个元素,nextNode()在HashIterator中实现。返回的是final类型,所以迭代器遍历返回值不能修改。
public final K next() { return nextNode().key; }
}
abstract class HashIterator {
Node next; // next entry to return
Node current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
//4 modCount 是HashMap的成员变量,记录修改次数。增加、删除、清空元素都会加1. 把当前的修改次数赋值给expectedModCount
expectedModCount = modCount;
Node[] 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);
}
}
public final boolean hasNext() {
return next != null;
}
final Node nextNode() {
Node[] t;
Node e = next;
//5 每一次返回元素,都会检查数量是否相同。如果不相同,则报异常。
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;
}
public final void remove() {
Node p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
K key = p.key;
removeNode(hash(key), key, null, false, false);
expectedModCount = modCount;
}
}
由上,可知,在遍历过程中,引起modCount变化的会抛异常。但put(k,v), 如果k已经存在呢?
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node 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 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)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
// 1 如果key已经存在,会更新value,并返回旧的value,但不会更改modCount
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
因此,迭代器可以修改已经存在的key的value,不会抛出异常。
但ConcurrentHashMap使用弱一致性迭代器,不检查修改次数。
为什么两个Map选用不同的迭代器?
HashMap是线程不安全的,使用fail-fast? 但synchronizedMap是线程安全的,使用的也是fail-fast。我觉得迭代过程中,更多的是要遍历,而不是为了修改,fail-fast 是常态。 concurrentHashMap使用弱一致性迭代器,遍历时,可以修改,增加了不确定性,这需要我使用时注意。