java高并发写入问题

List<String> list = new ArrayList<>();

使用ArrayList对数据进行赋值,会出现不同线程争抢同一资源造成写入失败问题,会抛出异常“ConcurrentModificationException”
List<String> list = new Vector<>();
List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList();
#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();
        }
    }

猜你喜欢

转载自www.cnblogs.com/ttyypjt/p/12601864.html