1. /** The lock protecting all mutators */
  2. final transient ReentrantLock lock = new ReentrantLock();

容器

  1. private transient volatile Object[] array;
  2. final Object[] getArray() { return array; }
  3. final void setArray(Object[] a) { array = a; }

add

  1. /**
  2. * Appends the specified element to the end of this list.
  3. *
  4. * @param e element to be appended to this list
  5. * @return {@code true} (as specified by {@link Collection#add})
  6. */
  7. public boolean add(E e) {
  8. final ReentrantLock lock = this.lock;
  9. lock.lock();
  10. try {
  11. Object[] elements = getArray();
  12. int len = elements.length;
  13. Object[] newElements = Arrays.copyOf(elements, len + 1);
  14. newElements[len] = e;
  15. setArray(newElements);
  16. return true;
  17. } finally {
  18. lock.unlock();
  19. }
  20. }

写入时复制

Arrays.copyOf(elements, len + 1)
在修改的时候复制资源,而不是把资源加锁,这样读取操作不会被阻塞。

优点:
读多写少时,可以实现更高并发。(Vector 增删改查都加了锁)

缺点:
只能保证数据最终一致性。
内存占用问题,如果对象较大,频繁复制可能会引发 Full GC,这时候 可以考虑 ConcurrentHashMap