当前位置:网站首页>多线程场景下使用 ArrayList 丢数据

多线程场景下使用 ArrayList 丢数据

2022-06-09 20:45:00 叮当的猫猫

前言

在这里插入图片描述

ArrayList 不是线程安全的

ArrayList 的 add 操作源码

  /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */
    public boolean add(E e) {
    
      // 判断列表的capacity容量是否足够,是否需要扩容
      ensureCapacityInternal(size + 1);  // Increments modCount!!
      // 将元素添加进列表的元素数组里面
      elementData[size++] = e;
      return true;
}

可能出现的问题

数组越界异常 ArrayIndexOutOfBoundsException

由于 ArrayList 添加元素是如上面分两步进行,可以看出第一个不安全的隐患,在多个线程进行add操作时可能会导致elementData数组越界

具体逻辑如下:

列表大小为9,即size=9
线程A 开始进入add方法,这时它获取到 size 的值为9,调用 ensureCapacityInternal 方法进行容量判断。
线程B 此时也进入add方法,它获取到 size 的值也为9,也开始调用 ensureCapacityInternal 方法。
线程A 发现需求大小为10,而 elementData 的大小就为10,可以容纳。于是它不再扩容,返回。
线程B 也发现需求大小为10,也可以容纳,返回。
线程A 开始进行设置值操作, elementData[size++] = e 操作。此时size变为10。

线程B 也开始进行设置值操作,它尝试设置 elementData[10] = e
而 elementData 没有进行过扩容,它的下标最大为9
于是此时会报出一个数组越界的异常ArrayIndexOutOfBoundsException.

元素值覆盖和为空问题

elementData[size++] = e 设置值的操作同样会导致线程不安全。从这儿可以看出,这步操作也不是一个原子操作,它由如下两步操作构成:

elementData[size] = e;
size = size + 1;

在单线程执行这两条代码时没有任何问题,但是当多线程环境下执行时,可能就会发生一个线程的值覆盖另一个线程添加的值,具体逻辑如下:

列表大小为0,即size=0
线程A 开始添加一个元素,值为A。此时它执行第一条操作,将 A 放在了 elementData 下标为0 的位置上。
接着 线程B 刚好也要 开始添加一个值为 B 的元素,且走到了第一步操作。此时 线程B 获取到 size 的值 依然为0,于是它将B也 放在了elementData下标为0 的位置上。

线程A 开始将size的值增加为 1
线程B 开始将size的值增加为 2
这样线程AB执行完毕后,理想中情况为size为2,elementData下标0 的位置为A,下标1 的位置为B。

而实际情况变成了 size 为2,elementData下标为0 的位置变成了 B,下标1 的位置上什么都没有。
并且后续除非使用set方法修改此位置的值,否则将一直为null
因为size为2,添加元素时会从下标为2的位置上开始。

代码示例

@SneakyThrows
public static void threadTest() {
    
    final List<Integer> list = new ArrayList<>();
    new Thread(() -> {
    
        for (int i = 1; i < 1000; i++) {
    
            list.add(i);
            System.out.println("添加第 " + i + "个元素 :" + i);
            try {
    
                Thread.sleep(1);
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }
    }).start();

    new Thread(() -> {
    
        for (int i = 1001; i < 2000; i++) {
    
            list.add(i);
            System.out.println("添加第 " + i + "个元素 :" + i);
            try {
    
                Thread.sleep(1);
            } catch (InterruptedException e) {
    
                e.printStackTrace();
            }
        }
    }).start();

    Thread.sleep(3000);
    System.out.println("list size:" + list.size());
}

执行过程中,两种情况出现如下:

1、元素值覆盖和为空问题
2、报数组越界异常 ArrayIndexOutOfBoundsException 错误

代码示例2

public static void main(String[] args) {
    
    List<Integer> list = new ArrayList<>();
     for (int i = 10000000; i >= 1; i--) {
    
         list.add(0);
     }
     System.out.println("源集合数量:"+list.size());
     List<Integer> newList = new ArrayList<>();
     long start = System.currentTimeMillis();

     ExecutorService executor = Executors.newFixedThreadPool(100);
     for (Integer integer : list) {
    
         executor.submit(()->{
    
             newList.add(integer+1);
         });
     }
     executor.shutdown();
     try {
    
         executor.awaitTermination(6, TimeUnit.MINUTES);
     } catch (InterruptedException e) {
    
         e.printStackTrace();
     }
     long end = System.currentTimeMillis();
     System.out.println("时间:"+(end-start)+"ms");

     System.out.println("新集合数量:"+newList.size());
}
public static void main(String[] args) {
    
    ArrayList<Integer> list = Lists.newArrayList();
    for (int i = 10000000; i >= 1; i--) {
    
        list.add(0);
    }
    System.out.println("源集合数量:" + list.size());
    Stopwatch started = Stopwatch.createStarted();
    List<Integer> newList = new ArrayList<>();
    ForkJoinPool forkJoinPool = new ForkJoinPool(100, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
    list.forEach(item ->
            CompletableFuture.runAsync(() -> {
    
                newList.add(item + 1);
            }, forkJoinPool)
    );
    System.out.println("时间:" + started.elapsed(TimeUnit.SECONDS));
    System.out.println("新集合数量:" + newList.size());
}

使用线程池给 ArrayList 添加一千万个元素。来看下结果:

在这里插入图片描述
数据会少于一千万

因为 ArrayList 不是线程安全的,在高并发情况下对list进行数据添加会出现数据丢失的情况。
并且 一个线程在遍历List , 另一个线程 修改List ,会报 ConcurrentModificationException (并发修改异常)错误

ArrayList线程安全处理

Collections.synchronizedList

最常用的方法是通过 Collections 的 synchronizedList 方法将 ArrayList 转换成线程安全的容器后再使用

List<Object> list = Collections.synchronizedList(new ArrayList<>());
list.add()方法加锁

代码示例2 使用 synchronizedList时间上和 Vector差距不大,因给给ArrayList进行了包装以后等于是给ArrayList 里面所有的方法都加上了 synchronized,和Vector实现效果差不多

在这里插入图片描述

list 方法加锁

synchronized(list.get()) {
    
      list.get().add(model);
}

Vector

使用 Vector 类进行替换,将上文的public static List arrayList = new ArrayList();替换为public static List arrayList = new Vector<>();

原理: 使用了synchronized关键字进行了加锁处理

public synchronized boolean add(E e) {
    
        modCount++;
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = e;
        return true;
 }

代码示例2 使用 Vector ,时间上要长于ArrayList

在这里插入图片描述

CopyOnWriteArrayList

使用线程安全的 CopyOnWriteArrayList 代替线程不安全的 ArrayList

List<Object> list = new CopyOnWriteArrayList<Object>();

原理: 使用mutex对象进行维护处理,Object mutex = new Object() 就是创建了一个临时空间用于辅助独占的处理

ThreadLocal

使用 ThreadLocal 使用ThreadLocal变量确保线程封闭性(封闭线程往往是比较安全的, 但由于使用ThreadLocal封装变量,相当于把变量丢进执行线程中去,每new一个新的线程,变量也会new一次,一定程度上会造成性能[内存]损耗,但其执行完毕就销毁的机制使得ThreadLocal变成比较优化的并发解决方案)。

ThreadLocal<List<Object>> threadList = new ThreadLocal<List<Object>>() {
    
        @Override
         protected List<Object> initialValue() {
    
              return new ArrayList<Object>();
         }
 };

其他

涉及到并发问题 参考 CountDownLatch

原网站

版权声明
本文为[叮当的猫猫]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_40813329/article/details/125168544