Netty源碼分析---MpscLinkedQueue

Netty源碼分析—MpscLinkedQueue

 MpscLinkedQueue是netty自己實現的線程安全的隊列,與JDK通過鎖實現的LinkedBlockingQueue不同,MpscLinkedQueue是一種針對Netty中NIO任務設計的一種隊列,允許有多個生產者,只有一個消費者的隊列。MpscLinkedQueue源碼註釋如下:

1. 一個無鎖的支持單消費者多生產者的併發隊列;

2. 允許多個生產者同時進行以下操作:offer(Object),add(Object),addAll(Collection);

3. 只允許一個消費者進行以下操作:poll(),remove(),remove(Object),clear();

4. 以下方法不支持:remove(Object o),removeAll(Collection),retainAll(Collection);

生產者生產數據

 多個生產者生產數據元素的方法如下:

public boolean add(E e) {
        if (offer(e)) {
            return true;
        }
        throw new IllegalStateException("queue full");
    }
public boolean offer(E value) {
        if (value == null) {
            throw new NullPointerException("value");
        }
		
		// 如果傳入的是node則直接使用,否則實例化一個newTail
        final MpscLinkedQueueNode<E> newTail;
        if (value instanceof MpscLinkedQueueNode) {
            newTail = (MpscLinkedQueueNode<E>) value;
            newTail.setNext(null);
        } else {
            newTail = new DefaultNode<E>(value);
        }

        MpscLinkedQueueNode<E> oldTail = replaceTail(newTail);
        oldTail.setNext(newTail);
        return true;
    }

private MpscLinkedQueueNode<E> replaceTail(MpscLinkedQueueNode<E> node) {
        return getAndSet(node);
    }
 
 //採用原子更新的方式來添加節點
public final V getAndSet(V newValue) {
        return (V)unsafe.getAndSetObject(this, valueOffset, newValue);
    }
消費者消費數據

 單個消費者消費數據的方法如下

  public E poll() {
       //獲取鏈表中的第一個元素
        final MpscLinkedQueueNode<E> next = peekNode();
        if (next == null) {
            return null;
        }

        // 下一個節點變成新的頭結點
        MpscLinkedQueueNode<E> oldHead = headRef.get();
        // 直接將此次獲取到的數據修改成頭結點
        headRef.lazySet(next);

        // 將原頭結點的next置爲null,去除oldHead與新頭結點之間的關聯
        oldHead.setNext(null);
        
        // 獲取節點中的數據,並將value置爲null,去除節點與數據直接的關聯
        return next.clearMaybe();
    }

  //獲取鏈表中的第一個元素
  private MpscLinkedQueueNode<E> peekNode() {
        for (;;) {
            final MpscLinkedQueueNode<E> head = headRef.get();
            final MpscLinkedQueueNode<E> next = head.next();
           
            // 當頭結點與尾節點不同時,說明肯定已經有數據插入了;
            if (next != null) {
                return next;
            }
           
            // 頭結點與尾節點相同,說明還在初始化狀態,直接返回null
            if (head == getTail()) {
                return null;
            }
        }
    }
總結

 MpscLinkedQueue通過使用鏈表存儲數據以及巧妙的CAS操作,實現單消費者多生產者隊列,代碼簡潔高效,適合netty中的無鎖化串行設計。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章