http://m.blog.csdn.net/blog/luoyuyou/38039599java
ConcurrentLinkedQueue是一個基於鏈表實現的非阻塞隊列,特色是head和tail是能夠滯後的,甚至tail落到head的後面,準確得說,是當事實的head距離當前head至少兩個link時纔會修改head,這種設計能夠在某些時候提升效率。node
咱們接着來看源碼實現,這裏主要是offer和poll方法:.net
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) { // p is last node if (p.casNext(null, newNode)) { if (p != t) // hop two nodes at a time casTail(t, newNode); // Failure is OK. return true; } // Lost CAS race to another thread; re-read next } else if (p == q) p = (t != (t = tail)) ? t : head; else // Check for tail updates after two hops. p = (p != t && t != (t = tail)) ? t : q; } }
public E poll() { restartFromHead: for (;;) { for (Node<E> h = head, p = h, q;;) { E item = p.item; if (item != null && p.casItem(item, null)) { if (p != h) // hop two nodes at a time updateHead(h, ((q = p.next) != null) ? q : p); return item; } else if ((q = p.next) == null) { updateHead(h, p); return null; } else if (p == q) continue restartFromHead; else p = q; } } }