CHM没有ConcurrentModificationException.为什么?

sgo*_*les 4 java hashmap map hashcode concurrenthashmap

我最近做了一个例子,我ConcurrentHashMap在迭代它时添加了元素.

代码段 -

Map<String, String> map = new ConcurrentHashMap<String, String>();
map.put("ABC", "abc");
map.put("XYZ", "xyz");
map.put("MNO", "mno");
map.put("DEF", "def");
map.put("PQR", "pqr");

Iterator<Map.Entry<String, String>> entrySet = map.entrySet().iterator();
while(entrySet.hasNext()) {
        Map.Entry<String, String> entry = entrySet.next();
        System.out.println(entry.getKey()+", "+entry.getValue());
        map.put("TQR", "tqr");
}
Run Code Online (Sandbox Code Playgroud)

但是我无法找到为什么代码在CHM情况下不会抛出ConcurrentModificationException的确切原因.

简而言之,与HashMap不同,CHM不会抛出ConcurrentModificationException.

谢谢!

Evg*_*eev 9

ConcurrentHashMap API声明其迭代器不会抛出ConcurrentModificationException.这是因为它的迭代器反映了迭代器创建时哈希表的状态.这就像它的迭代器使用哈希表快照一样:

    ConcurrentHashMap m = new ConcurrentHashMap();
    m.put(1, 1);
    Iterator i = m.entrySet().iterator();
    m.remove(1);        // remove entry from map      
    System.out.println(i.next()); //still shows entry 1=1
Run Code Online (Sandbox Code Playgroud)