即使是线程安全的集合,使用iterator()进行迭代都是不安全的,必须手动地进行同步,下面是JavaDoc的说明:
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:
Map m = Collections.synchronizedMap(new HashMap());
...
Set s = m.keySet(); // Needn't be in synchronized block
...
synchronized (m) { // Synchronizing on m, not s!
Iterator i = s.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
如果不使用同步块进行迭代,当在迭代时,如果存在另外一个线程对集合进行删除或者添加元素,则会报
ConcurrentModificationException
搜一下:什么具体情况下的插入删除能导致ConcurrentHashMap线程不安全?