[Java] Brief description of CopyOnWriteArrayList

CopyOnWriteArrayList is a thread-safe list (List) implementation in the Java standard library. It has some significant differences from ordinary ArrayList, mainly reflected in the concurrency of its read and write operations.
CopyOnWrityArrayList is also implemented internally through arrays. When adding elements to it, a new array will be copied. Writing operations are performed on the new array, and reading operations are performed on the original array.

It will be locked when writing to prevent data loss caused by concurrency.

Advantages : Because read operations do not require locking, its performance is better than traditional thread-safe queues under the condition of more reads and less writes.

Disadvantages : Because each write operation creates a new copy array, the write operation is expensive and may cause a large memory footprint. Therefore, it is not suitable for frequent writing operations.

usage

import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteArrayListExample {
    
    
    public static void main(String[] args) {
    
    
        CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();

        list.add(1);
        list.add(2);
        list.add(3);

        // 使用迭代器遍历
        for (Integer item : list) {
    
    
            System.out.println(item);
        }

        // 写操作
        list.add(4);

        // 迭代器遍历不会受到写操作的影响
        for (Integer item : list) {
    
    
            System.out.println(item);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_67548292/article/details/132202198