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