CopyonWriteArrayList

CopyonWriteArrayList is a class provided in the java concurrent package, based on the idea of ​​copy-on-write.
Ordinary ArrayList or Vector (although vector is thread-safe, but composite operation is not, after deleting or adding elements, its structure changes, modcount still changes, and an exception occurs), if there are two threads, one thread performs Iterator iterative display, while another thread performs the add or reomve operation, the iterative display operation will report a ConcurrentModificationException exception. It means that other threads cannot iterate over this list when a common list is being written.
When CopyonWriteArrayList performs add or remove (Object) operations, it first copies the array, then operates on the new array, and finally points the pointer of the original array to the new array.

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

However, CopyonWriteArrayList also has problems: 1. The operation cost of copying the entire array is relatively high; 2. The problem of weak data consistency, when reading and writing operations at the same time, the read data may not be the latest data.
CopyonWriteArrayList is suitable for reading more and writing less.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325900941&siteId=291194637