/**
* a thread-safe variant of {@link java.util.arraylist} in which all mutative
* operations ({@code add}, {@code set}, and so on) are implemented by
* making a fresh copy of the underlying array.
* <p>this is ordinarily too costly, but may be <em>more</em> efficient
* than alternatives when traversal operations vastly outnumber
* mutations, and is useful when you cannot or don't want to
* synchronize traversals, yet need to preclude interference among
* concurrent threads. the "snapshot" style iterator method uses a
* reference to the state of the array at the point that the iterator
* was created. this array never changes during the lifetime of the
* iterator, so interference is impossible and the iterator is
* guaranteed not to throw {@code concurrentmodificationexception}.
* the iterator will not reflect additions, removals, or changes to
* the list since the iterator was created. element-changing
* operations on iterators themselves ({@code remove}, {@code set}, and
* {@code add}) are not supported. these methods throw
* {@code unsupportedoperationexception}.
**/
/** the lock protecting all mutators **/
final transient reentrantlock lock = new reentrantlock();
/** the array, accessed only via getarray/setarray. **/
private transient volatile object[] array;
下面看一下主要方法。get方法如下。get方法没有什么特殊之处,不加锁,直接读取即可。
/**
* {@inheritdoc}
* @throws indexoutofboundsexception {@inheritdoc}
**/
public e get(int index) {
return get(getarray(), index);
}
/**
* gets the array. non-private so as to also be accessible
* from copyonwritearrayset class.
**/
final object[] getarray() {
return array;
}
@suppresswarnings("unchecked")
private e get(object[] a, int index) {
return (e) a[index];
}
/**
* 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;
}