Java CopyOnWriteArrayList

CopyOnWriteArrayList是一种线程安全的列表实现,避免并发修改异常。其工作原理是在修改时复制原数组创建新数组,确保读写分离。在添加元素时,它会在锁保护下进行,确保数据一致性。然而,这种机制消耗内存,可能导致频繁的垃圾回收,并不适用于实时读取。适用场景是读多写少的情况,但须注意大量数据可能导致频繁复制的性能问题。
摘要由CSDN通过智能技术生成

Why we use it?

  • Since the ArrayList is not thread-safely, it will cause ConcurrentModificationException when we modify the array in a concurrent situation, so we choose to use CopyOnWriteArrayList

What does CopyOnWrite means?

  • It means copy the array to create a same one when you want to modify it, and seperate the read and write

  • That is to copy the original array to write on a separate copy, so this does not affect the read on the original array; Once written, point the original array reference to the new array.

  • The entire ADD operation is done under the protection of the lock.This is to avoid making multiple copies when adding multiple threads concurrently, which will mess up the data and cause the final array data to be not what we expect.

  • If there are concurrent reads from a thread, there are several cases:

    1. If the write operation is not completed, then directly read the data of the original array;
    2. If the write is complete, but the reference does not point to the new array, then the original array data is also read;
    3. If the write is complete and the reference is already pointing to the new array, read the data directly from the new array.

Source code of ADD method

/**
 * 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; // create a lock, this guarantee safe when concurrent happen
    lock.lock();
    try {
        Object[] elements = getArray();// get the original array
        int len = elements.length; // get the length of original array
        Object[] newElements = Arrays.copyOf(elements, len + 1); // capacity + 1
        newElements[len] = e; // add operation 
        setArray(newElements); // update the array
        return true;
    } finally {
        lock.unlock();
    }
}

CopyOnWriteArrayList’s disadvantage

  • Since the write operation copies the array, it consumes memory and may cause young GC or full GC if the original array is too large
  • Cannot be used for real-time reading, such as copying array and adding new elements, it takes time, so after calling a set operation, the data read may still be old. Although CopyOnWriteArrayList can achieve the final consistency, it still cannot meet the real-time requirements.

CopyOnWriteArrayList is suitable for the scenario of reading more than writing, but this type is used with caution.Because there is no way to guarantee how much data CopyOnWriteArrayList will put into it, in case the data get too much and the array has to be re-copied every time add/set, this is too expensive.In high-performance Internet applications, this operation can cause a failure in minutes.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值