锁
/** The lock protecting all mutators */
final transient ReentrantLock lock = new ReentrantLock();
容器
private transient volatile Object[] array;
final Object[] getArray() { return array; }
final void setArray(Object[] a) { array = a; }
add
/**
* 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();
}
}
写入时复制
Arrays.copyOf(elements, len + 1)
在修改的时候复制资源,而不是把资源加锁,这样读取操作不会被阻塞。
优点:
读多写少时,可以实现更高并发。(Vector 增删改查都加了锁)
缺点:
只能保证数据最终一致性。
内存占用问题,如果对象较大,频繁复制可能会引发 Full GC,这时候 可以考虑 ConcurrentHashMap