LinkedBlockingQueue源碼分析

1. 變量和構造方法

private final int capacity; // 容量(最大節點個數),默認Integer.MAX_VALUE
private final AtomicInteger count = new AtomicInteger(); // 當前節點個數
transient Node<E> head; // 隊列頭結點
private transient Node<E> last; // 隊列尾節點
private final ReentrantLock takeLock = new ReentrantLock(); // 頭結點鎖(取)
private final Condition notEmpty = takeLock.newCondition(); // 等待隊列非空
private final ReentrantLock putLock = new ReentrantLock(); // 尾結點鎖(置)
private final Condition notFull = putLock.newCondition(); // 等待隊列非滿

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}

public LinkedBlockingQueue(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    this.capacity = capacity;
    last = head = new Node<E>(null); // 頭節點不存放元素
}

public LinkedBlockingQueue(Collection<? extends E> c) {
    this(Integer.MAX_VALUE);
    final ReentrantLock putLock = this.putLock;
    putLock.lock(); // 尾結點加鎖
    try {
        int n = 0;
        for (E e : c) {
            if (e == null)
                throw new NullPointerException();
            if (n == capacity) // 隊列滿
                throw new IllegalStateException("Queue full");
            enqueue(new Node<E>(e));
            ++n;
        }
        count.set(n);
    } finally {
        putLock.unlock(); // 釋放鎖
    }
}

2. 生產(put、offer)

static class Node<E> { // 節點
    E item;
    Node<E> next;
    Node(E x) { item = x; }
}

private void enqueue(Node<E> node) {
    last = last.next = node;
}

private void signalNotEmpty() { // 在獲取takeLock狀態下,喚醒等待get的線程
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
}

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly(); // 加鎖
    try {
        while (count.get() == capacity) { // 隊列滿
            notFull.await();
        }
        enqueue(node);
        c = count.getAndIncrement(); // 必須是原子操做 if (c + 1 < capacity) // put後,隊列非滿
            notFull.signal(); // 喚醒後續等待put的線程(若是存在)
    } finally {
        putLock.unlock(); // 釋放鎖
    }
    if (c == 0) // put前,隊列空
        signalNotEmpty(); // 喚醒首個等待get的節點(若是存在)
}

public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    long nanos = unit.toNanos(timeout);
    int c = -1;
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;
    putLock.lockInterruptibly(); // 加鎖
    try {
        while (count.get() == capacity) { // 隊列滿
            if (nanos <= 0) // 超時(awaitNanos可能已被signal,但在SyncQueue中排隊等鎖時超時,見ReentrantLock)
                return false;
            nanos = notFull.awaitNanos(nanos); // 等待(在nanos時間內)
        }
        enqueue(new Node<E>(e));
        c = count.getAndIncrement();
        if (c + 1 < capacity) // offer後,隊列非滿
            notFull.signal(); // 喚醒後續等待offer的線程(若是存在)
    } finally {
        putLock.unlock(); // 釋放鎖
    }
    if (c == 0) // offer前,隊列爲空
        signalNotEmpty(); // 喚醒首個等待get的線程(若是存在)
    return true;
}

3. 消費(take、poll)

private E dequeue() {
    Node<E> h = head;
    Node<E> first = h.next;
    h.next = h; // help GC
    head = first;
    E x = first.item;
    first.item = null;
    return x;
}

private void signalNotFull() { // 在獲取putLock鎖狀態下,喚醒等待put的線程
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        notFull.signal();
    } finally {
        putLock.unlock();
    }
}

public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly(); // 加鎖
    try {
        while (count.get() == 0) { // 隊列空
            notEmpty.await(); // 等待
        }
        x = dequeue();
        c = count.getAndDecrement();
        if (c > 1) // get後,隊列非空
            notEmpty.signal(); // 喚醒後續等待get線程(若是存在)
    } finally {
        takeLock.unlock(); // 釋放鎖
    }
    if (c == capacity) // get前,隊列已滿
        signalNotFull(); // 喚醒首個等待put的線程(若是存在)
    return x;
}

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    E x = null;
    int c = -1;
    long nanos = unit.toNanos(timeout);
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lockInterruptibly(); // 加鎖
    try {
        while (count.get() == 0) { // 隊列空
            if (nanos <= 0) // 超時
                return null;
            nanos = notEmpty.awaitNanos(nanos); // 等待poll
        }
        x = dequeue();
        c = count.getAndDecrement();
        if (c > 1) // poll後,隊列非空
            notEmpty.signal(); // 喚醒後續等待poll的線程(若是存在)
    } finally {
        takeLock.unlock(); // 釋放鎖
    }
    if (c == capacity) // poll前,隊列已滿
        signalNotFull(); // 喚醒首個等待put的線程(若是存在)
    return x;
}

4. 加全鎖(remove)

void fullyLock() { // 加全鎖(remove、contains、toArray、clear、Itr)
    putLock.lock();
    takeLock.lock();
}

void fullyUnlock() { // 釋放全鎖
    takeLock.unlock();
    putLock.unlock();
}

void unlink(Node<E> p, Node<E> trail) {
    p.item = null;
    trail.next = p.next;
    if (last == p)
        last = trail;
    if (count.getAndDecrement() == capacity) // 移除節點前,隊列已滿
        notFull.signal(); // 喚醒等待put/offer的線程
}

public boolean remove(Object o) { // 刪除節點
    if (o == null) return false;
    fullyLock(); // 加全鎖
    try {
        for (Node<E> trail = head, p = trail.next; p != null; trail = p, p = p.next) {
            if (o.equals(p.item)) {
                unlink(p, trail);
                return true;
            }
        }
        return false;
    } finally {
        fullyUnlock(); // 釋放全鎖
    }
}
相關文章
相關標籤/搜索