使用countDownLatch导致的线程安全问题,线程不安全的List-ArrayList,线程安全的List-CopyOnWriteArrayList

示例代码

java 复制代码
package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UnSafeCDTest {

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 20; i++){
            UnSafeCDTest unSafeCDTest = new UnSafeCDTest();
            unSafeCDTest.test();
        }

    }


    public void test() throws InterruptedException {
        List<String> list = new ArrayList<>();
      //  List<String> list = new CopyOnWriteArrayList<>();
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> {
                // TODO
                list.add("1" );
                // TODO
                // cd
                countDownLatch.countDown();

            });
        }
        countDownLatch.await();
        System.out.println( list.size());

    }
}

输出结果

image.png

可以看到有一个结果为4;

修改ArrayList为线程安全的List,CopyOnWriteArrayList;

验证结果

image.png

CopyOnWriteArrayList为什么是线程安全的

查看源码可以看到通过了加锁实现了线程安全

复制代码
/**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            int len = elements.length;
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }
相关推荐
文丑颜不良啊1 小时前
LeetCode3101~3120题目解析
java·leetcode
Resean02231 小时前
SpringMVC 6+源码分析(十一)视图渲染与异步请求(收尾篇)
java·spring·springmvc
starzy19902 小时前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
靠沿2 小时前
MySQL数据库进阶——存储过程和触发器
java·数据库·mysql
码少女3 小时前
MySQL--库与表的增删改查基础
java·数据库·mysql
布莱克6054 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环
敲上瘾4 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
Flynt4 小时前
掘金热文说 Spring Boot 4.1 默认开虚拟线程,我实测后发现了更狠的坑
java·spring boot·性能优化
联犀5 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
Resean02235 小时前
Spring 源码分析(一)IOC 容器总览与 refresh() 全景
java·后端·spring