posts - 35,  comments - 8,  views - 18万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

一、ConcurrentModificationException

ArrayList源码看为什么出现异常:

复制代码
public class ArrayList<e> extends AbstractList<e>
        implements Cloneable, Serializable, RandomAccess {
         
         
         @Override public boolean remove(Object object) {
        Object[] a = array;
        int s = size;
        if (object != null) {
            for (int i = 0; i < s; i++) {
                if (object.equals(a[i])) {
                    System.arraycopy(a, i + 1, a, i, --s - i);
                    a[s] = null;  // Prevent memory leak
                    size = s;
                    modCount++;  // 只要删除成功都是累加
                    return true;
                }
            }
        } else {
            for (int i = 0; i < s; i++) {
                if (a[i] == null) {
                    System.arraycopy(a, i + 1, a, i, --s - i);
                    a[s] = null;  // Prevent memory leak
                    size = s;
                    modCount++;  // 只要删除成功都是累加
                    return true;
                }
            }
        }
        return false;
    }   
 
 
    @Override public Iterator<e> iterator() {
        return new ArrayListIterator();
    }   
         
    private class ArrayListIterator implements Iterator<e> {
          ......
    
          // 全局修改总数保存到当前类中
        /** The expected modCount value */
        private int expectedModCount = modCount;
 
        @SuppressWarnings("unchecked") public E next() {
            ArrayList<e> ourList = ArrayList.this;
            int rem = remaining;
               // 如果创建时的值不相同,抛出异常,
            if (ourList.modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            if (rem == 0) {
                throw new NoSuchElementException();
            }
            remaining = rem - 1;
            return (E) ourList.array[removalIndex = ourList.size - rem];
        }   
         
          ......
     }
}
复制代码

  由上可知,如果遍历中作get,remove操作都会改变modCount的值,但是此时expectedModCount还是保存以前的modCount的值,肯定不相等,抛出异常。

二、多线程下的异常

1、发生 ArrayIndexOutOfBoundsException 异常;

  问题是出现在多线程并发访问下,由于没有同步锁的保护,造成了 ArrayList 扩容不一致的问题。

2、程序正常运行,输出了少于实际容量的大小;

  这个也是多线程并发赋值时,对同一个数组索引位置进行了赋值,所以出现少于预期大小的情况。

3、程序正常运行,输出了预期容量的大小;

  这是正常运行结果,未发生多线程安全问题,但这是不确定性的,不是每次都会达到正常预期的。

三、线程安全的CopyOnWriteArrayList

Java并发集合(一)-CopyOnWriteArrayList分析与使用

 

posted on   程序员自我修养张振力  阅读(1234)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示