美文网首页
CopyOnWriteArrayList

CopyOnWriteArrayList

作者: 晨曦_lcq | 来源:发表于2020-06-29 00:00 被阅读0次

ArrayList VS Vector VS CopyOnWriteArrayList

  • ArrayList 线程不安全
  • Vector 线程安全,但是用synchronized修饰的方法,性能不行
  • CopyOnWriteArrayList 兼顾了线程安全和性能

继承关系

CopyOnWriteArrayList.png

解析:

  • 属性
    final transient ReentrantLock lock = new ReentrantLock();
    // 元素
    private transient volatile Object[] array;
  • 线程安全,操作元素都加了锁
public E set(int index, E element) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object[] elements = getArray();
            E oldValue = get(elements, index);

            if (oldValue != element) {
                int len = elements.length;
                Object[] newElements = Arrays.copyOf(elements, len);
                newElements[index] = element;
                setArray(newElements);
            } else {
                // Not quite a no-op; ensures volatile write semantics
                setArray(elements);
            }
            return oldValue;
        } finally {
            lock.unlock();
        }
    }
``

相关文章

网友评论

      本文标题:CopyOnWriteArrayList

      本文链接:https://www.haomeiwen.com/subject/nhknfktx.html