在随后的博文中我会继续分析并发包源码,在这里,得分别谈谈容器类和迭代器及其源码,虽然很突兀,但我认为这对于学习Java并发很重要;
ConcurrentModificationException:
JavaAPI中的解释:当不允许这样的修改时,可以通过检测到对象的并发修改的方法来抛出此异常。一个线程通常不允许修改集合,而另一个线程正在遍历它。 一般来说,在这种情况下,迭代的结果是未定义的。 某些迭代器实现(包括由JRE提供的所有通用集合实现的实现)可能会选择在检测到此行为时抛出此异常。 这样做的迭代器被称为"及时失败"迭代器,当他们发现容器在迭代时被修改时,就会报异常;它称不上时一种处理机制,而是一种预防机制,只能作为并发问题的预警指示器.
迭代器与容器:
Vector这个"古老"的容器类相信大家很熟悉了,他是线程安全的没错,我们利用elements()方法遍历,不会出现线程安全的问题:
1 /** 2 * JDK1.8源码 3 */ 4 5 /** 6 * Returns an enumeration of the components of this vector. The 7 * returned {@code Enumeration} object will generate all items in 8 * this vector. The first item generated is the item at index {@code 0}, 9 * then the item at index {@code 1}, and so on. 10 * 11 * @return an enumeration of the components of this vector 12 * @see Iterator 13 */ 14 public Enumeration<E> elements() { 15 return new Enumeration<E>() { 16 int count = 0; 17 18 public boolean hasMoreElements() { 19 return count < elementCount; 20 } 21 22 public E nextElement() { 23 synchronized (Vector.this) { 24 if (count < elementCount) { 25 return elementData(count++); 26 } 27 } 28 throw new NoSuchElementException("Vector Enumeration"); 29 } 30 }; 31 }