Iterator、Iterable、快速失败机制
先用ArrayList引出它们吧,看下关系图
简述:
ArrayList 有个内部类迭代器 Itr,Itr 实现了Iterator接口
ArrayList 实现了Iterable接口,实现该接口。允许对象使用迭代器进行遍历和 forEach 方式进行遍历
一、内部类迭代器 Itr
1.几个重要的属性:
- cursor:返回的下一个元素的索引
- lastRet:最后返回的元素的索引
- expectedModCount:期望的modCount,用于快速失败机制
2.什么是快速失败机制?
最常见的例子,多个线程同时操作一个集合时,A线程在遍历集合(首先把epModCount=modCount),B线程在操作(添加/删除)集合的元素。都会对modCount++,
A线程每遍历一个元素就会判断modCount是否等于epModCount。不等于就结束遍历,报ConcurrentModificationException
异常
看例子:
往list里面丢了100个元素,然后遍历。x=3时,使用
list
的remove()
方法删掉这个元素由于add了100次,此时modCount=100
// 单线程下其实一样,只要调用forEach,就会检测modCount
@Test
public void test2(){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add(i);
}
list.forEach(x->{
// 在遍历的同时,改变了list的结构。会包并发修改异常, 是如何发现的? 看forEach
if(x == 3){
// list.add(122); 只要对list进行结构性操作,就会改变modCount
list.remove(x);
}
});
System.out.println(list);
}
点进ForEach()方法查看
- 首先把
expectedModCount = modCount
,当前modCount=expectedModCount=100
- 遍历的时候,每次判断modCount == expectedModCount,不相等就结束
// ArrayList
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
// 把modCount赋值给expectedModCount
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
// 再遍历的时候,每次判断modCount == expectedModCount
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
// 不相等
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
再查看list.remove()
,
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
// 在这里
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
// 在这里
fastRemove(index);
return true;
}
}
return false;
}
查看fastRemove(index)
先对 modCount+1
此时,modCount=101,而expectedModCount=100
private void fastRemove(int index) {
// 进行删除,就会对modCount++
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
所以当remove()后,迭代器遍历时会发现这2个不同。报ConcurrentModificationException
异常
3.Itr 的源码:
/**
* An optimized version of AbstractList.Itr
*/
private class Itr implements Iterator<E> {
int cursor; // 下一个要返回的元素的索引
int lastRet = -1; // 最后一个返回的元素的索引; 如果没有,=-1 在调用next()时候会维护这个属性
int expectedModCount = modCount; // 用于检测是否被多个线程同时修改
Itr() {}
public boolean hasNext() {
// 判断集合是否还有下一个元素
return cursor != size;
}
// 并发修改检查,每进行next(),remove()都会调用这个方法,判断ArrayList是否被其他线程修改过。如果有->抛并发异常
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
@SuppressWarnings("unchecked")
public E next() {
// 并发修改检查
checkForComodification();
// 返回元素的索引
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
// 继续判断list是否被修改过,如果另一个线程把list的元素都删了。就会出现这种情况(并发修改
if (i >= elementData.length)
throw new ConcurrentModificationException();
// 计算下一个返回的索引
cursor = i + 1;
// 给lastRet赋值=当前返回元素的索引 然后,返回元素
return (E) elementData[lastRet = i];
}
public void remove() {
// 说明还没有调用next(),没有开始遍历
if (lastRet < 0)
throw new IllegalStateException();
// 并发修改检查
checkForComodification();
try {
// 内部还是调用ArrayList自己的remove(int index)方法,删除最后返回的元素
// 可能会抛出 “索引越界异常”
ArrayList.this.remove(lastRet);
// lastRet位置元素被删除,后面左移,维护cursor
cursor = lastRet;
// 没有返回元素,lastRet 置为-1
lastRet = -1;
// ???这是为什么呢?
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
// 从 cursor 开始遍历后面剩余的元素
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
// 并发修改检测
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// update once at end of iteration to reduce heap write traffic
cursor = i;
lastRet = i - 1;
checkForComodification();
}
}
ArrayList自己的remove(int index)
方法
- 删除此列表中指定位置的元素。将所有后续元素向左移动(从其索引中减去一个)。
- 没有则抛出 “索引越界异常”
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
forEachRemaining(Consumer<? super E> consumer)
对集合剩余元素的遍历操作
示例>>:先使用迭代器遍next()
方法遍历了2个,然后剩下的使用forEachRemaining(Customer c)
方法遍历
public class Demo1 {
@Test
public void test(){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
Iterator<Integer> it = list.iterator();
int count = 2;
while (it.hasNext()){
System.out.println(it.next());
count--;
if(count == 1)
break;
}
System.out.println("--------------遍历剩余元素");
it.forEachRemaining(System.out::println);
}
}
结果:
0
1
--------------遍历剩余元素
2
3
4
5
6
7
8
9
4.如何一边遍历,一边删除元素?迭代器
可假设迭代器位于2个元素之间
-
删除元素remove()
-
next方法:返回刚刚越过的那个元素的引用:
- remove方法:会借助
lastRet
删除上次调用next方法时返回的元素
Iterator<String> it = c.iterator();
it.next();
it.remove(); //ok--删除一个元素
//删除2个元素
it.remove();
it.remove(); //Error
it.next();
it.remove();
it.next();
it.remove(); //ok
- 删除所有元素
public static void removeAll(ArrayList<Integer> list){
Iterator<Integer> it = list.iterator();
while(it.hasNext()){
it.next();
it.remove();
}
}
如有错误,请大家指正