concurrent- ConcurrentLinkedQueue

ConcurrentLinkedQueue使用了Unsafe的cas机制保证了线程的安全,用peek方法为例

 

public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
        implements Queue<E>, java.io.Serializable {
		private static final sun.misc.Unsafe UNSAFE;
	    private transient volatile Node<E> head;
		private transient volatile Node<E> tail;
		
	    private boolean casHead(Node<E> cmp, Node<E> val) {
			return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
		}
	
		//以peek为例,
		public E peek() {
			restartFromHead:
			for (;;) {
				for (Node<E> h = head, p = h, q;;) {
					E item = p.item;
					//当找到值,或者到最后一个节点的时候
					if (item != null || (q = p.next) == null) {
					    //判断head是不是和原来的一样,如果一样将P设置为head
						updateHead(h, p);
						return item;
					}
					else if (p == q)
						continue restartFromHead;
					else
						p = q;
				}
			}
		}
		
	    /**
		 * Try to CAS head to p. If successful, repoint old head to itself
		 * as sentinel for succ(), below.
		 */
		final void updateHead(Node<E> h, Node<E> p) {
			if (h != p && casHead(h, p))			    
				h.lazySetNext(h);
		}
}

你可能感兴趣的:(Concurrent)