An overview of the

Java and send the thread-safe list provided in the package, that is, CopyOnWriteArrayList

The problem

How CopyOnWriteArrayList is thread safe. CopyOnWriteArrayList has no limit on its length. Why CopyOnWriteArrayList is a copy-on-write collection.

The add method

public boolean add(E e) { //1. Final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); //2. Get Object[] int len = elements. Length; Object[] newElements = array.copyof (Elements, len + 1); NewElements [len] = e; //5. Add elements to the new element setArray(newElements); //6. Return true; } finally { lock.unlock(); }} Final Object[] getArray() {return array; }

How does CopyOnWriteArrayList make writing thread-safe? Because ReentrantLock is used as an exclusive lock, the data is stored in the Array array in CopyOnWriteArrayList to ensure that only one thread is modifying the collection at the same time. When adding an element to an array, you do not add the element directly to the array. Instead, you copy a new array with a length of [the length of the old array +1] and replace the old array with the new array.

Weak consistency

The use of iterators

Source:

When we call the iterator method to get an iterator, we call the COWIterator constructor internally. The constructor takes two arguments. The first argument is array, and the second argument is subscript 0. The array array is then assigned to the snapshot variable in the constructor. “Snapshot” means “snapshot”. If you are familiar with Java, you should know that the array is a reference type and that Pointers are passed. If there are other changes to the array, this should be reflected immediately. Yes, if another thread does not add, subtract, or delete CopyOnWriteArrayList, then snapshot is its own array. But if another thread adds, subtract, or delete CopyOnWriteArrayList, the old array will be replaced by the new array. But snapshot is still a reference to the old array. That is, when we use iterators to facilitate CopyOnWriteArrayList, there is no guarantee that the data we get is up to date, which is also a weak consistency issue.

This time we changed the order of the code, first fetching iterators, then deleting threads, and finally iterating through the iterators. Result: You can see that the deleted element is still printed.