关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

JUC-集合

发布时间:2023-06-26 14:00:13

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 NodenewNode = new Node(e);  for (Nodet = tail, p = t;;) {  Nodeq = 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(局部锁,不是全局锁)保证线程安全

/template/Home/leiyu/PC/Static