為什么阿里巴巴java開(kāi)發(fā)手冊(cè)這么規(guī)定?

關(guān)注我,精彩文章第一時(shí)間推送給你

公眾號(hào).jpg

12-e7c4a452-0

  • 首先我嘗試寫(xiě)了一下這段代碼如下:
private static void testForeachAddOrRemove() {
    var list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    for (var s : list) {
        if ("2".equals(s)) {
            list.remove(s);
        }
    }
    list.forEach(System.out::println);
}

調(diào)用結(jié)果:異常ConcurrentModificationException如下:

12-e7c4a452-1
  • 如圖所示提示ArrayList.java 1043行拋出異常,我用的JDK11,馬上點(diǎn)進(jìn)去看了源碼,正是如下這行拋出的異常,原因是modCount != expectedModCount那么這兩個(gè)變量什么意思呢?繼續(xù)讀源碼
final void checkForComodification() {
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}
  • modCount是在抽象類(lèi)AbstractList中被定義,是集合結(jié)構(gòu)修改的次數(shù),例如添加元素、刪除元素等結(jié)構(gòu)調(diào)整都會(huì)使modCount++,下面列舉add()和刪除的源碼,其他結(jié)構(gòu)化修改也會(huì)modCount++,這里不做列舉。
public boolean remove(Object o) {
    final Object[] es = elementData;
    final int size = this.size;
    int i = 0;
    found: {
        if (o == null) {
            for (; i < size; i++)
                if (es[i] == null)
                    break found;
        } else {
            for (; i < size; i++)
                if (o.equals(es[i]))
                    break found;
        }
        return false;
    }
    fastRemove(es, i);//-----------重點(diǎn)重點(diǎn)重點(diǎn)------------------
    return true;
}
private void fastRemove(Object[] es, int i) {
    modCount++;//---------------重點(diǎn)重點(diǎn)重點(diǎn)------------------
    final int newSize;
    if ((newSize = size - 1) > i)
        System.arraycopy(es, i + 1, es, i, newSize - i);
    es[size = newSize] = null;
}
public boolean add(E e) {
        modCount++;//-------重點(diǎn)重點(diǎn)重點(diǎn)----------
        add(e, elementData, size);
        return true;
    }
  • expectedModCount是在ArrayList的內(nèi)部類(lèi)Itr中聲明的,Itr實(shí)現(xiàn)類(lèi)迭代器接口,這里做了下精簡(jiǎn)只保留了變量聲明和next()方法、remove()方法,可以看到迭代器的實(shí)現(xiàn)里聲明了expectedModCount = modCount;這里理解成預(yù)期結(jié)構(gòu)化調(diào)整次數(shù) = 結(jié)構(gòu)化調(diào)整次數(shù),為什么每次迭代next()和remove()之前都要檢查是否相等呢?可以理解成如果沒(méi)有這個(gè)校驗(yàn),某個(gè)線程刪除了list的一個(gè)元素,此時(shí)next方法不知道size變更了,依然去取數(shù)組里的數(shù)據(jù),會(huì)導(dǎo)致數(shù)據(jù)為null或ArrayIndexOutOfBoundsException異常等問(wèn)題。
/**
     * An optimized version of AbstractList.Itr
     */
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;//-------------重點(diǎn)重點(diǎn)重點(diǎn)---------------

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();//-------------重點(diǎn)重點(diǎn)重點(diǎn)------------------
        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();//-----------重點(diǎn)重點(diǎn)重點(diǎn)---------------------

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;//------------重點(diǎn)重點(diǎn)重點(diǎn)-------------------
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)//-----------重點(diǎn)重點(diǎn)重點(diǎn)---------------------
            throw new ConcurrentModificationException();
    }
}
  • 這里串起來(lái)就好理解了,由于增強(qiáng)for循環(huán)底層反編譯之后是迭代器實(shí)現(xiàn)的,所以在iterator初始化的時(shí)候(也就是for循環(huán)開(kāi)始處),expectedModCount = modCount之后for循環(huán)內(nèi)部進(jìn)行remove實(shí)際上用的是ArrayList的remove()方法,執(zhí)行了modCount++,而進(jìn)行for循環(huán)底層進(jìn)行next()迭代的時(shí)候進(jìn)行了checkForComodification()方法判斷,modCount++了next()并不知道,所以造成不相等拋出異常。
  • 那為什么使用迭代器可以進(jìn)行刪除而不拋出異常呢?因?yàn)榭瓷厦娴脑创a,迭代器內(nèi)部的remove()方法的實(shí)現(xiàn)在調(diào)用ArrayList.this.remove()進(jìn)行刪除之后,expectedModCount = modCount;及時(shí)同步了這兩個(gè)變量的值。所以使用迭代器刪除不會(huì)造成問(wèn)題,寫(xiě)法如下:
private static void testForeachAddOrRemove() {
    var list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    /*for (var s : list) {
        if ("2".equals(s)) {
            list.remove(s);
        }
    }*/
    var iterator = list.iterator();
    while (iterator.hasNext()) {
        var str = iterator.next();
        if ("2".equals(str)) {
            iterator.remove();
        }
    }
    list.forEach(System.out::println);
}

建議:如果是JDK8或者以上版本,推薦使用removeIf進(jìn)行刪除,這也是IDEA推薦寫(xiě)法

寫(xiě)法如下:

private static void testForeachAddOrRemove() {
    var list = new ArrayList<String>();
    list.add("1");
    list.add("2");
    /*for (var s : list) {
            if ("2".equals(s)) {
                list.remove(s);
            }
        }*/
    
    /*var iterator = list.iterator();
    while (iterator.hasNext()) {
        var str = iterator.next();
        if ("2".equals(str)) {
            iterator.remove();
        }
    }*/

    list.removeIf("2"::equals);
    list.forEach(System.out::println);
}
  • 同樣可以閱讀一下removeIf()的源碼
@Override
public boolean removeIf(Predicate<? super E> filter) {
    return removeIf(filter, 0, size);
}

/**
     * Removes all elements satisfying the given predicate, from index
     * i (inclusive) to index end (exclusive).
     */
boolean removeIf(Predicate<? super E> filter, int i, final int end) {
    Objects.requireNonNull(filter);
    int expectedModCount = modCount;//-----------重點(diǎn)重點(diǎn)重點(diǎn)--------------
    final Object[] es = elementData;
    // Optimize for initial run of survivors
    for (; i < end && !filter.test(elementAt(es, i)); i++)
        ;
    // Tolerate predicates that reentrantly access the collection for
    // read (but writers still get CME), so traverse once to find
    // elements to delete, a second pass to physically expunge.
    if (i < end) {
        final int beg = i;
        final long[] deathRow = nBits(end - beg);
        deathRow[0] = 1L;   // set bit 0
        for (i = beg + 1; i < end; i++)
            if (filter.test(elementAt(es, i)))
                setBit(deathRow, i - beg);
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        modCount++;//-------------重點(diǎn)重點(diǎn)重點(diǎn)------------
        int w = beg;
        for (i = beg; i < end; i++)
            if (isClear(deathRow, i - beg))
                es[w++] = es[i];
        shiftTailOverGap(es, w, end);
        return true;
    } else {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        return false;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容