copyOnWriteArray 记录一下
package java.util.concurrent;//你没有看错,是这个包
private transient volatile Object[] array;//初始化数组 public CopyOnWriteArrayList() {//构造函数,初始化 setArray(new Object[0]); } final void setArray(Object[] a) { array = a; } 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(); } } final Object[] getArray() { return array; }
public E get(int index) {//获取单个数组对象 return get(getArray(), index); }
private E get(Object[] a, int index) { return (E) a[index]; }
add的时候枷锁,先复制,后赋值;get的时候并没有加锁,(导致多线程的时候可能get不到最近的值)