原文:
不要在 foreach 循环里进行元素的 remove/add 操作。remove 元素请使用 Iterator 方式,如果并发操作,需要对 Iterator 对象加锁。
理解:
这里要避免的还是线程安全问题,要知道ArrayList,LinkedList, HashMap等常用集合都不是线程安全的,当我们使用foreach遍历集合的时候,底层走的是对Iterator接口的实现。使用迭代器遍历的这个操作是必须要保证列表数据的唯一,所以不能在迭代器遍历的时候去修改列表数据。
证明:
在AbstractList中,定义了modCount这样一个变量, modify count 字面理解的意思是修改次数,当我们在add, remove等操作都会在源码中看到这个变量加一。
它的作用就是用来标识迭代过程中列表数据是否是不变的。
protected transient int modCount = 0;
看Iterator的实现(ArrayList):
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
// prevent creating a synthetic constructor
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int size = ArrayList.this.size;
int i = cursor;
if (i < size) {
final Object[] es = elementData;
if (i >= es.length)
throw new ConcurrentModificationException();
for (; i < size && modCount == expectedModCount; i++)
action.accept(elementAt(es, i));
// update once at end to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
从源码中可以看出,在实例化Iterator对象的时候,expectedModCount 被初始化为 modCount, 在每一次next()操作和remove操作的时候,都会调用checkForComodification()去检查modCount是否等于expectedModCount,进而判断列表数据是否被修改。如果不等,那么抛出异常。
例子:
remove的错误操作。
list.remove()操作修改了list对象的modCount, 在foreach的时候,被checkForComodification()方法检测到。
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
for (String item : list) {
if ("1".equals(item)) {
list.remove(item);
}
}
正确的remove
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String item = iterator.next();
if (删除元素的条件) {
iterator.remove();
}
}
add操作:
开启两个线程,一个线程add,一个线程迭代遍历。
List<Integer> list = new ArrayList<>();
int N = 100000;
new Thread(()->{
for (int i = 0; i < N; i++) {
list.add(i);
}
}).start();
new Thread(()->{
for (Integer integer : list) {
System.out.println(integer);
}
}).start();
再看一个例子:
这个例子中,迭代器遍历的线程被wait了,需要等待add操作的线程执行完毕才能开启。
List<Integer> list = new ArrayList<>();
int N = 10000;
new Thread(()->{
for (int i = 0; i < N; i++) {
list.add(i);
}
synchronized (list){
list.notify();
}
}).start();
new Thread(()->{
synchronized (list) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (Integer integer : list) {
System.out.println(integer);
}
}).start();
上面的例子进一步说明了在使用迭代器遍历的时候需要保证列表数据的唯一,其实还是一个线程安全问题。