Home > Java > javaTutorial > body text

How to use java's CopyOnWriteArrayList?

PHPz
Release: 2023-05-09 22:55:25
forward
1382 people have browsed it

Concept

1. CopyOnWriteArrayList is a concurrent container provided in the Java concurrency package. It is a thread-safe and lock-free ArrayList for reading operations. It creates a new copy of the underlying array. Implementing writing operations is a concurrency strategy that separates reading and writing. We can also call it "copy-on-write".

2. CopyOnWriteArrayList allows concurrent reading without locking. The most important thing is that it does not affect reading when writing, because when writing, copying the original array and operating on the new array does not affect the original array at all. Only multiple writings are synchronized. I think it's very similar to the multi-version concurrency mechanism of a database.

Example

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

The above is the detailed content of How to use java's CopyOnWriteArrayList?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!