Thread-safe List

The most commonly used lists in Java are ArrayList and LinkedList, but these two threads are not thread-safe, and thread-safe lists need to be considered in the case of multithreading

Vector

Vector was added in JDK 1.0 and has a long history; The underlying principle is almost the same as ArrayList, except that synchronized is added to each of Vector’s exposed methods to ensure concurrency security, but its performance is very low and it is not recommended

Collections.synchronizedList()

The Collections collection utility class provides a method to convert lists into thread-safe synchronizedLists

public static <T> List<T> synchronizedList(List<T> list)
Copy the code

The principle is simply to add synchronized to each method to ensure thread-safety, which is more flexible than Vector extensibility

public E get(int index) { synchronized (mutex) {return list.get(index); } } public E set(int index, E element) { synchronized (mutex) {return list.set(index, element); } } public void add(int index, E element) { synchronized (mutex) {list.add(index, element); } } public E remove(int index) { synchronized (mutex) {return list.remove(index); }}Copy the code

CopyOnWriteArrayList & CopyOnWriteArraySet

Using copy-on-write (COW) to implement thread-safe collection, the advantage is that there are ready to modify, there are still other threads can read the disadvantage is a waste of space, each time to add and delete elements need to copy a new array

Public Boolean add(E E) {synchronized (lock) {public Boolean add(E E) {synchronized (lock) {Object[] es = getArray(); Int len = es. Length; es = Arrays.copyOf(es, len + 1); // Add elements to end es[len] = e; // Copy the changes back to setArray(es); return true; }}Copy the code