CopyOnWriteArrayList和synchronizedList之间的区别 [英] Difference between CopyOnWriteArrayList and synchronizedList

查看:295
本文介绍了CopyOnWriteArrayList和synchronizedList之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,并发集合类优先于同步集合,因为并发集合类不对整个集合对象采取锁定。

As per my understanding concurrent collection classes preferred over synchronized collections because the concurrent collection classes don't take a lock on the complete collection object. Instead they take locks on a small segment of the collection object.

但是当我检查添加方法时, code> CopyOnWriteArrayList ,我们正在获取一个完整的收集对象的锁。那么 CopyOnWriteArrayList 是如何优于 Collections.synchronizedList 返回的列表的?我在 add 添加 CopyOnWriteArrayList 方法中看到的唯一区别是我们每次创建 add 方法。

But when I checked the add method of CopyOnWriteArrayList, we are acquiring a lock on complete collection object. Then how come CopyOnWriteArrayList is better than a list returned by Collections.synchronizedList? The only difference I see in the add method of CopyOnWriteArrayList is that we are creating copy of that array each time the add method is called.

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();
    }
}


推荐答案

write(add)操作,CopyOnWriteArrayList使用 ReentrantLock 并创建数据的备份副本,并且底层volatile数组引用只通过setArray(在setArray将在添加之前返回旧数据之前对列表进行任何读取操作)进行更新。此外,CopyOnWriteArrayList还提供快照故障安全但是当我检查了CopyOnWriteArrayList.class的add方法时,我们获取了锁定,而不是在写入/添加上抛出ConcurrentModifficationException。

For write (add) operation, CopyOnWriteArrayList uses ReentrantLock and creates a backup copy of the data and the underlying volatile array reference is only updated via setArray(Any read operation on the list during before setArray will return the old data before add).Moreover, CopyOnWriteArrayList provides snapshot fail-safe iterator and doesn't throw ConcurrentModifficationException on write/ add.

完整的收集对象。那么怎么CopyOnWriteArrayList比synchronizedList好。我们在CopyOnWriteArrayList的add方法中看到的唯一区别是每次调用add方法时都会创建该数组的副本。

But when I checked add method of CopyOnWriteArrayList.class, we are acquiring lock on complete collection object. Then how come CopyOnWriteArrayList is better than synchronizedList. The only difference I see in add method of CopyOnWriteArrayList is we are creating copy of that array each time add method get called.




  1. 否,锁不是在整个Collection对象上。如上所述,这是一个 ReentrantLock < a>,并且它与内部对象锁定不同。

  2. add方法将始终创建现有数组的副本,然后对副本进行修改,最后更新数组的volatile引用以指向此新数组。这就是为什么我们有名称CopyOnWriteArrayList - 当你写入它时复制。这也避免了ConcurrentModificationException

这篇关于CopyOnWriteArrayList和synchronizedList之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆