java集合之List线程安全性比较总结(性能比较)

前言

介绍三种安装es-head插件的方式
1、Google浏览器插件 安装Google浏览器插件,直接访问Elasticsearch
2、npm安装 下载源码,编译安装,在nodejs环境下运行插件


一、背景

在多线程中使用集合list时,会有线程不安全的问题。所以调研了所有的list线程安全的集合,同时使用简单的测试,测试出相对应的性能。
线程安全的list :

List<Integer> vector = new Vector<>();
List<Integer> listSyn = Collections.synchronizedList(new ArrayList<>());
List<Integer> copyList = new CopyOnWriteArrayList<>();

二、测试

package com.example.jkytest.juc;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

public class ListTest {
    
    


    // static List<Integer> list = new ArrayList<>();

    static List<Integer> vector = new Vector<>();
    static List<Integer> listSyn = Collections.synchronizedList(new ArrayList<>());
    static List<Integer> copyList = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws InterruptedException {
    
    
        // 设置并发数
        int num = 100;
        List<List<Integer>> all = Arrays.asList(vector, listSyn, copyList);
        for (List<Integer> list : all) {
    
    
            long start = System.currentTimeMillis();
            test(num, list);
            System.out.println("------耗时:" + (System.currentTimeMillis() - start));
            // 等待上述所有线程执行完
            Thread.sleep(2 * 1000);
        }
    }

    /**
     * @param num  循环次数
     * @param list 集合
     */
    public static void test(int num, List<Integer> list) {
    
    
        for (int i = 0; i < num; i++) {
    
    
            new Thread(() -> list.add(Math.round(0))).start();
        }
    }
}

执行的结果:

并发数 100 1000 10000
Vector 74 148 836
Collections 11 49 716
CopyOnWriteArrayList 14 59 512

三、详解

  • ArrayList线程不安全:主要是多线程在写入数据时,会有重复写入的问题

  • Vector线程安全:主要是在添加元素的时候,加上了synchronized

public synchronized E set(int index, E element) {
    
    
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
 
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }
  • Collections.synchronizedList:主要是一个大的集合框架里面也是synchronized
        public boolean add(E e) {
    
    
            synchronized (mutex) {
    
    return c.add(e);}
        }
  • CopyOnWriteArrayList:主要是使用ReentrantLock,每次添加元素都会复制旧的数据到新的数组里面,同时使用锁
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();
        }
}

四、总结

ArrayList 单线程中使用

多线程中,并发在2000以内的使用Collections.synchronizedList;并发在2000以上的使用CopyOnWriteArrayList;Vector是JDK1.1版本就有的集合是一个重量级的,不建议使用


总结

如果此篇文章有帮助到您, 希望打大佬们能关注点赞收藏评论支持一波,非常感谢大家!
如果有不对的地方请指正!!!

参考1

猜你喜欢

转载自blog.csdn.net/weixin_42326851/article/details/130708305