描述
ConcurrentLinkedQueue是一个基于单链表的无界线程安全队列,该队列是FIFO的。ConcurrentLinkedQueue/ConcurrentLinkedDeue和LinkedBlockingQueue/LinkedBlockingDeue
相比,不同点在于它们是non-blocking的,并且是lock-free的,而后者则是利用ReentrantLock实现的,所以他们具有更高的吞吐量。
源码解析(基于jdk1.8.0_40)
数据结构
类图:
head,tail结点定义和描述:
/**
* A node from which the first live (non-deleted) node (if any)
* can be reached in O(1) time.
* Invariants:
* - all live nodes are reachable from head via succ()
* - head != null
* - (tmp = head).next != tmp || tmp != head
* Non-invariants:
* - head.item may or may not be null.
* - it is permitted for tail to lag behind head, that is, for tail
* to not be reachable from head!
*/
private transient volatile Node<E> head;
/**
* A node from which the last node on list (that is, the unique
* node with node.next == null) can be reached in O(1) time.
* Invariants:
* - the last node is always reachable from tail via succ()
* - tail != null
* Non-invariants:
* - tail.item may or may not be null.
* - it is permitted for tail to lag behind head, that is, for tail
* to not be reachable from head!
* - tail.next may or may not be self-pointing to tail.
*/
private transient volatile Node<E> tail;
链表结构
构造函数,初始化时让head和tail同时指向一个dummy结点(否则入队时需要同时修改head,tail 2个指针,需要加锁。而有了dummy