JUC对于集合的支持
- CopyOnWriteArrayList
- ArrayList线程安全的变体
- 基于ReentrantLock可重入锁、数组复制保证线程安全
- 不会引发ConcurrentModificationException
- 不支持迭代器,会抛出UnsupportedOperationException
- 部分代码如下
public boolean add(E e) { final ReentrantLock lock = this.lock; //注意这里,基于ReentrantLock lock.lock(); try { Object[] elements = getArray(); int len = elements.length; //数字copy Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } }
- • ConcurrentLinkedQueue
- 无界线程安全队列
- 基于CAS保证线程安全
public boolean offer(E e) { checkNotNull(e); final Node<E> newNode = new Node<E>(e); for (Node<E> t = tail, p = t;;) { Node<E> q = p.next; if (q == null) { //注意这里,通过CAS新增节点 if (p.casNext(null, newNode)) { if (p != t) // hop two nodes at a time casTail(t, newNode); // Failure is OK. return true; } } else if (p == q) p = (t != (t = tail)) ? t : head; else p = (p != t && t != (t = tail)) ? t : q; } }
- ConcurrentHashMap
- HashMap的线程安全变体
- 基于CAS、synchronized(局部锁,不是全局锁)保证线程安全