成员变量
final transient ReentrantLock lock = new ReentrantLock(); // add 方法时加速,保证只有一个线程写private transient volatile Object[] array; // 保存元素,volatile 修饰保证可见性,线程对其的修改 happens before 后面对这个数组引用的读
方法
get 方法
没有加锁,直接返回数组元素
public E get(int index) {return get(getArray(), index);}@SuppressWarnings("unchecked")private E get(Object[] a, int index) {return (E) a[index];}
add 方法
通过 ReentrantLock 来保证只有一个线程能写,利用 Arrays.copy 复制元素到新数组,然后最后直接返回新数组
/*** Appends the specified element to the end of this list.** @param e element to be appended to this list* @return {@code true} (as specified by {@link Collection#add})*/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();}}/*** Sets the array.*/final void setArray(Object[] a) {array = a;}
