為了將讀取的性能發(fā)揮到極致商架,JDK提供了此類:相比與讀寫鎖,寫入不會(huì)阻塞讀取操作兔簇,讀取操作也不會(huì)阻塞寫入操作。只有在寫入和寫入之間需要進(jìn)行同步等待。因此在讀操作遠(yuǎn)多于寫操作的情況下垄琐,效率極高边酒。
讀操作相關(guān)源碼:完全無鎖
@SuppressWarnings("unchecked")
private E get(Object[] a, int index) {
return (E) a[index];
}
/**
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
return get(getArray(), index);
}
- 寫操作源碼:
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (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();
}
}