it编程 > 编程语言 > Java

Java Arraylist在多线程环境下的问题与解决方案

1人参与 2026-03-19 Java

一、arraylist 的线程不安全性

arraylist 的所有方法都没有进行同步控制,多个线程同时添加、删除、修改同一个 arraylist 实例时,会导致:

list<integer> list = new arraylist<>();
executorservice executor = executors.newfixedthreadpool(10);
for (int i = 0; i < 1000; i++) {
    executor.submit(() -> list.add(1));
}
executor.shutdown();
// 结果:可能抛出异常,或最终 size 不等于 1000

二、为什么它是线程不安全的

arraylist 是线程不安全的,根本原因在于其内部实现没有对共享数据的并发访问进行任何同步控制,导致多线程同时修改时会出现数据竞争。

2.1 内部数据结构

arraylist 底层是一个 object 数组elementdata)和一个 int 类型的 size 字段,用于记录实际元素个数:

所有修改操作如 addremove都会直接操作这个数组和 size。

2.2 并发添加时的竞态条件

假设两个线程同时执行 list.add(e),该方法大致步骤如下:

public boolean add(e e) {
    ensurecapacityinternal(size + 1);  // 检查是否需要扩容
    elementdata[size++] = e;            // 插入元素并 size 自增
    return true;
}

1. 扩容检查

2. 数组越界异常

更常见的情况是:两个线程在扩容后都准备插入元素:

3. size 的非原子操作

size++ 实际上分为三步:读取 size → 加 1 → 写回 size。多线程环境下,这些步骤可能交错执行,导致:

三、实际测试

我们看一段如下的java代码

/**
 * 演示 arraylist 多线程并发问题
 */
@test
public void testarraylistconcurrencyissue() throws interruptedexception {
    list<integer> list = new arraylist<>();
    int threadcount = 5;
    countdownlatch latch = new countdownlatch(threadcount);

    // 创建 5 个线程,每个线程添加 1000 个元素
    for (int i = 0; i < threadcount; i++) {
        final int threadid = i;
        new thread(() -> {
            try {
                for (int j = 0; j < 1000; j++) {
                    list.add(threadid * 1000 + j);
                }
            } catch (exception e) {
                system.err.println("线程异常:" + e);
            } finally {
                latch.countdown();
            }
        }).start();
    }

    latch.await();

    system.out.println("预期大小:" + (threadcount * 1000));
    system.out.println("实际大小:" + list.size());
    system.out.println("丢失元素:" + (threadcount * 1000 - list.size()));
    
    if (list.size() < threadcount * 1000) {
        system.out.println("❌ 检测到线程安全问题:数据丢失!");
    }
}

其运行结果如下:

四、解决方案

关于arraylist多线程并发解决方案还是很多的,但是各有优缺点,我们来一个一个介绍。

4.1 collections.synchronizedlist 同步包装器

它是将普通 arraylist 转换为线程安全版本最直接的手段。synchronizedlist 的核心设计思路是 装饰器模式。它并没有重新实现一个 list,而是将原有的 arraylist 包裹起来,然后在每个方法的实现上都加上 synchronized 代码块,通过同一把 互斥锁 来保证线程安全。

// collections类中的静态内部类
static class synchronizedlist<e> extends synchronizedcollection<e> implements list<e> {
    final list<e> list;  // 被包装的原始arraylist

    synchronizedlist(list<e> list, object mutex) {
        super(list, mutex);  // 将mutex(锁对象)传给父类
        this.list = list;
    }

    public e get(int index) {
        synchronized (mutex) {  // 获取锁
            return list.get(index); // 调用原arraylist的方法
        }  // 释放锁
    }

    public void add(int index, e element) {
        synchronized (mutex) {  // 获取锁
            list.add(index, element); // 调用原arraylist的方法
        }  // 释放锁
    }
    
    // ... 其他所有方法都是同样的模式
}

优点

缺点

同时它也有着大量的其他问题,例如复合操作不具备原子性。即使使用了 synchronizedlist,下面这段代码在多线程环境下仍然是错误的:

list<string> list = collections.synchronizedlist(new arraylist<>());
// ... 假设list中已经有了一些元素

// 在多线程环境下执行这段代码
if (!list.contains("a")) {  // 检查操作(已加锁)
    list.add("b");          // 添加操作(已加锁)
}

contains 和 add 虽然是两个原子操作,但组合在一起就不是原子操作了。在 contains 检查通过后、add 执行之前,可能有另一个线程插进来添加了该元素,导致最终重复添加。

此时你需要手动使用同一个锁对象来保证复合操作的原子性:

// 正确做法:使用list对象本身作为锁,锁住整个操作块
synchronized (list) {
    if (!list.contains("特定元素")) {
        list.add("特定元素");
    }
}

因为 synchronizedlist 内部使用的是 this 作为锁,所以外部用 synchronized (list) 可以保证与内部方法使用的是同一把锁这个是多线程的知识点,如果有不会的可以翻翻我写的关于多线程的文章

其次的问题就是遍历时需要手动加锁。当使用迭代器遍历 synchronizedlist 时,必须在外层加锁。

list<string> list = collections.synchronizedlist(new arraylist<>());

// 错误示例:会抛出 concurrentmodificationexception
// 因为迭代器遍历期间,另一个线程可能修改了list
for (string item : list) { 
    // 处理item
}

// 正确示例
synchronized (list) {
    for (string item : list) { // 在锁的保护下遍历
        // 处理item
    }
}

这是因为 synchronizedlist 的 iterator() 方法本身并没有加锁,它返回的迭代器在遍历过程中,如果有其他线程修改了 list,依然会触发快速失败机制。

综上,如果在使用场景是读写比例均衡,或需要强一致性的场景,可以考虑使用collections.synchronizedlist,但是需要记住在遍历或者任何复合操作的情况下,都需要手动加锁来保证原子性。

/**
 * 使用 collections.synchronizedlist 解决并发问题
 */
@test
public void testsynchronizedlist() throws interruptedexception {
    list<integer> list = collections.synchronizedlist(new arraylist<>());
    int threadcount = 10;
    int opsperthread = 50000;
    countdownlatch latch = new countdownlatch(threadcount);

    long starttime = system.currenttimemillis();

    for (int i = 0; i < threadcount; i++) {
        final int threadid = i;
        new thread(() -> {
            try {
                for (int j = 0; j < opsperthread; j++) {
                    synchronized (list) {
                        list.add(threadid * opsperthread + j);
                    }
                }
            } finally {
                latch.countdown();
            }
        }).start();
    }

    latch.await();
    long endtime = system.currenttimemillis();

    system.out.println("预期大小:" + (threadcount * opsperthread));
    system.out.println("实际大小:" + list.size());
    system.out.println("执行时间:" + (endtime - starttime) + "ms");
    
    if (list.size() == threadcount * opsperthread) {
        system.out.println("✓ synchronizedlist 保证线程安全!");
    }
}

4.2 copyonwritearraylist 并发集合

这是java并发包(juc)中专门为读多写极少场景量身定做的一个方法。它的设计思想非常巧妙,采用了不变性写时复制策略,彻底解决了并发冲突的问题。

copyonwritearraylist 的核心思想非常简单直观:每当需要对列表进行修改(增、删、改)时,不直接修改原始数组,而是先复制一份快照,在快照上修改,修改完成后再将原数组的引用指向这个新的数组。

public class copyonwritearraylist<e> {
    // 关键:使用 volatile 修饰的数组,保证修改后对其他线程的可见性
    private transient volatile object[] array;

    // 添加元素的方法
    public boolean add(e e) {
        final reentrantlock lock = this.lock;
        lock.lock(); // 写操作必须加锁,防止并发修改时复制出多个副本
        try {
            object[] elements = getarray(); // 获取当前数组
            int len = elements.length;
            // 核心:复制一个新数组(长度+1)
            object[] newelements = arrays.copyof(elements, len + 1);
            newelements[len] = e; // 在新数组上执行添加操作
            setarray(newelements); // 将新数组设为当前数组
            return true;
        } finally {
            lock.unlock();
        }
    }

    // 读取元素的方法(没有加锁)
    public e get(int index) {
        return get(getarray(), index); // 直接从当前数组中获取
    }

    // 返回当前数组的快照
    final object[] getarray() {
        return array;
    }
}

这种设计带来的两个核心特性:

优点

缺点

综上,如果你的业务要求严格的实时一致性(比如支付扣款后的余额查询),copyonwritearraylist 就不适合了。

特性copyonwritearraylistcollections.synchronizedlist
实现原理空间换时间:写时复制,读写分离时间换安全:所有操作串行化
读锁无锁有锁(读读互斥)
写锁有锁(用reentrantlock控制)有锁
内存占用高(每次写创建新数组)
数据一致性弱一致性(迭代器快照)强一致性(锁保护)
迭代异常永不抛出 concurrentmodificationexception遍历期间如有修改会抛出异常
最佳场景读多写极少(配置、白名单、监听器列表)读写均衡,或需要强一致性的场景
/**
 * 演示使用 copyonwritearraylist 解决并发问题
 */
@test
public void testthreadsafelist() throws interruptedexception {
    list<integer> list = new copyonwritearraylist<>();
    int threadcount = 10;
    int opsperthread = 50000;
    countdownlatch latch = new countdownlatch(threadcount);

    long starttime = system.currenttimemillis();

    for (int i = 0; i < threadcount; i++) {
        final int threadid = i;
        new thread(() -> {
            try {
                for (int j = 0; j < opsperthread; j++) {
                    list.add(threadid * opsperthread + j);
                }
            } finally {
                latch.countdown();
            }
        }).start();
    }

    latch.await();
    long endtime = system.currenttimemillis();

    system.out.println("预期大小:" + (threadcount * opsperthread));
    system.out.println("实际大小:" + list.size());
    system.out.println("执行时间:" + (endtime - starttime) + "ms");
    
    if (list.size() == threadcount * opsperthread) {
        system.out.println("✓ 线程安全,数据完整!");
    }else {
        system.out.println("❌ 检测到线程安全问题:数据不完整!");
    }
}

通过上述代码可以看到,同样是50万量级的数据,使用copyonwritearraylist的运行插入的时间是collections.synchronizedlist好几百倍,所以我们一定要注意使用场景的问题。

我们再来用一个读多写少的场景对比一下

/**
 * 读多写少场景:synchronizedlist vs copyonwritearraylist
 */
@test
public void testreadheavyscenario() throws interruptedexception {
    int threadcount = 10;
    int writecount = 1000;
    int readcount = 1000000;

    system.out.println("=== synchronizedlist 读多写少 ===");
    long synctime = testsynchronizedlist(threadcount, writecount, readcount);

    system.out.println("\n=== copyonwritearraylist 读多写少 ===");
    long cowtime = testcopyonwritearraylist(threadcount, writecount, readcount);

    system.out.println("\n=== 性能对比 ===");
    system.out.println("synchronizedlist: " + synctime + "ms");
    system.out.println("copyonwritearraylist: " + cowtime + "ms");
    system.out.println("copyonwritearraylist " + (synctime > cowtime ? "更快" : "更慢") + 
                      ",提升了 " + string.format("%.2f", (double)(synctime - cowtime) / synctime * 100) + "%");
}

private long testsynchronizedlist(int threadcount, int writecount, int readcount) throws interruptedexception {
    list<integer> list = collections.synchronizedlist(new arraylist<>());
    countdownlatch latch = new countdownlatch(threadcount);
    long starttime = system.currenttimemillis();

    for (int i = 0; i < threadcount; i++) {
        final int threadid = i;
        new thread(() -> {
            try {
                for (int j = 0; j < writecount; j++) {
                    synchronized (list) {
                        list.add(threadid * writecount + j);
                    }
                }
                for (int j = 0; j < readcount; j++) {
                    synchronized (list) {
                        if (!list.isempty()) {
                            list.get(list.size() - 1);
                        }
                    }
                }
            } finally {
                latch.countdown();
            }
        }).start();
    }

    latch.await();
    long endtime = system.currenttimemillis();
    system.out.println("写+读执行时间:" + (endtime - starttime) + "ms,写大小:" + list.size());
    return endtime - starttime;
}

private long testcopyonwritearraylist(int threadcount, int writecount, int readcount) throws interruptedexception {
    list<integer> list = new copyonwritearraylist<>();
    countdownlatch latch = new countdownlatch(threadcount);
    long starttime = system.currenttimemillis();

    for (int i = 0; i < threadcount; i++) {
        final int threadid = i;
        new thread(() -> {
            try {
                for (int j = 0; j < writecount; j++) {
                    list.add(threadid * writecount + j);
                }
                for (int j = 0; j < readcount; j++) {
                    if (!list.isempty()) {
                        list.get(list.size() - 1);
                    }
                }
            } finally {
                latch.countdown();
            }
        }).start();
    }

    latch.await();
    long endtime = system.currenttimemillis();
    system.out.println("写+读执行时间:" + (endtime - starttime) + "ms,写大小:" + list.size());
    return endtime - starttime;
}

上面的程序是十个线程,写入1万,读100万,可以看到在读百万量级数据的时候,用copyonwritearraylist的时间几乎是提升了40倍。

以上就是java arraylist在多线程环境下的问题与解决方案的详细内容,更多关于java arraylist线程不安全性的资料请关注代码网其它相关文章!

(0)

您想发表意见!!点此发布评论

推荐阅读

Java实现获取两个日期之间的所有日期的开始时间集合

03-19

java检测一个字符串是否是时间格式

03-19

Java线程死锁的问题解决

03-19

SpringBoot中读取配置文件的6种方式总结

03-19

Java 并发编程基础概念与常见问题整理

03-19

Springboot 缓存@Cacheable 的引入和使用

03-19

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论