publicclassConcurrentLinkedQueue<E>extendsAbstractQueue<E>implementsQueue<E>, java.io.Serializable {privatestaticclassNode<E>{volatile E item;volatile Node<E> next;/**
* Constructs a new node. Uses relaxed write because item can
* only be seen after publication via casNext.
*/Node(E item){
UNSAFE.putObject(this, itemOffset, item);}booleancasItem(E cmp, E val){return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);}voidlazySetNext(Node<E> val){
UNSAFE.putOrderedObject(this, nextOffset, val);}booleancasNext(Node<E> cmp, Node<E> val){return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);}// Unsafe mechanicsprivatestaticfinal sun.misc.Unsafe UNSAFE;privatestaticfinallong itemOffset;privatestaticfinallong nextOffset;static{try{
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = Node.class;
itemOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("item"));
nextOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("next"));}catch(Exception e){thrownewError(e);}}}privatetransientvolatile Node<E> head;privatetransientvolatile Node<E> tail;
队列存储的结构为Node节点;
Node节点中的两个属性item和next都是 Volatile 类型,保证可见;
Node结构中,是通过 Unsafe类的CAS 操作来实现赋值等操作的。
构造函数
publicConcurrentLinkedQueue(){
head = tail =newNode<E>(null);}publicConcurrentLinkedQueue(Collection<?extendsE> c){
Node<E> h = null, t = null;for(E e : c){checkNotNull(e);
Node<E> newNode =newNode<E>(e);if(h == null)
h = t = newNode;else{
t.lazySetNext(newNode);
t = newNode;}}if(h == null)
h = t =newNode<E>(null);
head = h;
tail = t;}
publicbooleanoffer(E e){checkNotNull(e);final Node<E> newNode =newNode<E>(e);for(Node<E> t = tail, p = t;;){
Node<E> q = p.next;if(q == null){// p is last nodeif(p.casNext(null, newNode)){// Successful CAS is the linearization point// for e to become an element of this queue,// and for newNode to become "live".if(p != t)// hop two nodes at a timecasTail(t, newNode);// Failure is OK.returntrue;}// Lost CAS race to another thread; re-read next}elseif(p == q)// We have fallen off list. If tail is unchanged, it// will also be off-list, in which case we need to// jump to head, from which all live nodes are always// reachable. Else the new tail is a better bet.
p =(t !=(t = tail))? t : head;else// Check for tail updates after two hops.
p =(p != t && t !=(t = tail))? t : q;}}
首先看for循环的条件:for (Node t = tail, p = t; ; ) 表示自旋循环,直到插入元素成功才return true退出。
public E poll(){
restartFromHead:for(;;){for(Node<E> h = head, p = h, q;;){
E item = p.item;if(item != null && p.casItem(item, null)){// Successful CAS is the linearization point// for item to be removed from this queue.if(p != h)// hop two nodes at a timeupdateHead(h,((q = p.next)!= null)? q : p);return item;}elseif((q = p.next)== null){updateHead(h, p);return null;}elseif(p == q)continue restartFromHead;else
p = q;}}}