添加
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();
}
}
删除
public E remove(int index) {
final ReentrantLock lock = this.lock;
lock.lock();
try {//同步代码
Object[] elements = getArray();
int len = elements.length;
E oldValue = get(elements, index);
int numMoved = len - index - 1;
if (numMoved == 0)
setArray(Arrays.copyOf(elements, len - 1));//数组复制
else {
Object[] newElements = new Object[len - 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index + 1, newElements, index,
numMoved);
setArray(newElements);
}
return oldValue;
} finally {
lock.unlock();
}
}
获取
public E get(int index) {//基于volatile获取最新值
return get(getArray(), index);
}