关于java规范的一些思考一

在阅读java规范的时候有这么一条

【强制】不要在foreach循环里进行元素的remove/add操作。remove元素请使用Iterator方式,如果并发操作,需要对Iterator对象加锁。

之前自己没注意到这个地方,因此做了一个实验,分别看下面两段代码:

代码1

List a = new ArrayList();
a.add("1");
a.add("2");
for (String temp : a) {
    if("1".equals(temp)){
        a.remove(temp);
    }
}

代码2

List a = new ArrayList();
a.add("1");
a.add("2");
for (String temp : a) {
    if("2".equals(temp)){
        a.remove(temp);
    }
}

代码1正常运行,代码2运行错误,抛出 ConcurrentModificationException

错误代码如下,所示

Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:937)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:891)

霍霍,interesting,为何1出现问题,而2不出现问题呢。对比一下自己写的和反编译后的代码:

自己写的:                                                                
List a = new ArrayList();
a.add("1");
a.add("2");
for (String temp : a) {
    if("2".equals(temp)){
        a.remove(temp);
    }
}
 反编译的:
List a = new ArrayList();
a.add("1");
a.add("2");
Iterator var1 = a.iterator();

while(var1.hasNext()) {
    String temp = (String)var1.next();
 if ("2".equals(temp)) {
        a.remove(temp);
 }
}

很明显,foreach循环是一个语法糖,编译器最终还是通过iterator来便利的,要弄清楚问题原因,不妨追踪一下源码。

arraylist内部维护了一个私有 iterator 类

private class Itr implements Iterator
类存在三个变量

int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;

抛出的异常为ConcurrentModificationException,顾名思义,这个异常是为避免并发修改产生不可预料的错误而存在,但是这里并没有多线程,怎么也会出现这个问题呢?

在Itr内,我这段代码中,可能抛出异常的有两个部分

1

if (i >= elementData.length)
    throw new ConcurrentModificationException();

2

if (modCount != expectedModCount)
    throw new ConcurrentModificationException();

追踪代码容易发现问题出在2,也就是modCount和expectedModcount不一致,modcount是arralist成员变量,在调用ArrayList增删操作会修改modcount变量值,在我的代码中调用了a.remove()方法,最终调用ArrayList的fastremove也就是下面的代码

private void fastRemove(Object[] es, int i) {
    modCount++;
 final int newSize;
 if ((newSize = size - 1) > i)
        System.arraycopy(es, i + 1, es, i, newSize - i);
 es[size = newSize] = null;
}

显然,这段代码修改了modcount,因此两个值就不一致了,因此抛出ConcurrentModificationException异常。解决办法,也很容易了,只要保持两个值一致不就ok了吗。因此调用迭代器的remove方法,他会保证modcount和expectedmod值一致,如下第9行。

public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException();
 checkForComodification();

 try {
        ArrayList.this.remove(lastRet);
 cursor = lastRet;
 lastRet = -1;
第9行 expectedModCount = modCount;
 } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
 }
}

区别在于调用arraylist.remove 和 iterator.remove方法。

好了,虽然解决了,但是还有一个问题,为什么字符串2会出现问题,而字符串1就不会出现这个问题呢?

这个问题其实很简单,不妨看一下反编译的代码,容易发现,由于1处在第一个位置,而且列表大小刚好为2,移除1后,ArrayList的size大小为1,而且iterator的cursor也为1,因此hashnext返回false,不会继续执行,所以没问题。如果使用下面的代码,则无论是1还是2或者3都会出现问题。

List a = new ArrayList();
a.add("1");
a.add("2");
a.add("3");
for(String temp :a) {
    if ("1".equals(temp)) {
        a.remove(temp);
 }
}
System.out.println(a);

这里不得不吐槽一下,for each 逻辑移除代码本身并无问题,仅仅因为编译后生成的代码和库函数设计的问题产生bug,和程序员编码能力并无关系,如果说这是语言特色的话,我很想一巴掌呼过去,fuck java!!!!
我就是剁手,用汇编,转行也不写java了!
emmmm~~~ spring boot 真好用(^-^)

你可能感兴趣的:(关于java规范的一些思考一)