private transient volatile Object[] array;
public E get(int index) {
return get(getArray(), index);
}
final Object[] getArray() {
return array;
}
public E set(int index, E element) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
E oldValue = get(elements, index);
if (oldValue != element) {
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len);
newElements[index] = element;
setArray(newElements);
} else {
// Not quite a no-op; ensures volatile write semantics
setArray(elements);
}
return oldValue;
} finally {
lock.unlock();
}
}
final void setArray(Object[] a) {
array = a;
}
array是一个volatile变量,其读、写操作具有Happends-Before关系。具体来讲,线程W1通过set()方法“修改”集合后,线程R1能立刻通过get()方法得到array的最新值。
set()方法也很简单,两个要点:
1.通过锁lock保护队列修改过程
2.在副本上修改,最后替换array引用
网友评论