小白系列----LinkedBlockingQueue

LinkedBlockingQueue

  • 基于链表实现的阻塞队列,默认长度Integer.MAX_VALUE
  • 吞吐量通常比基于数组实现的高,但在同步应用的场景下性能更难预测

插入元素大致逻辑:

成员变量
// 存储节点的信息
static class Node<E> {
        E item;
        Node<E> next;
        Node(E x) { item = x; }
}
//  存储元素的空间大小,默认Integer.MAX_VALUE
private final int capacity;

// 当前队列元素的个数, 使用CAS来保证并发安全
private final AtomicInteger count = new AtomicInteger();

// 头结点,不变量:head.item = null
transient Node<E> head;

// 尾结点, 不变量:last.next = null
private transient Node<E> last;

// 获取元素 需要的锁
private final ReentrantLock takeLock = new ReentrantLock();

// 获取元素时, 当没有获取到资源时就会将线程放入该队列
private final Condition notEmpty = takeLock.newCondition();

// 添加元素 需要的锁
private final ReentrantLock putLock = new ReentrantLock();

// 添加元素时, 当队列元素已经满了,线程将会进入notFull等待队列
private final Condition notFull = putLock.newCondition();
offer() :

不返回异常

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final AtomicInteger count = this.count;
    // 当前链表长度是否已经达到最大
    if (count.get() == capacity)
        return false;
    int c = -1;
    // 为新元素创建Node节点
    Node<E> node = new Node<E>(e);
    // 获取添加元素的重入锁
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        // 链表未满
        if (count.get() < capacity) {
            // 添加节点到链表尾部
            enqueue(node);
            // 返回的是旧值
            c = count.getAndIncrement();
            // 判断此时是否达到链表最大长度
            if (c + 1 < capacity)
                // 唤醒等待添加元素的等待队列
                notFull.signal();
        }
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        // >= 0, 说明有元素,唤醒notEmpty等待队列的线程
        signalNotEmpty();
    return c >= 0;
}

private void enqueue(Node<E> node) {
    // assert putLock.isHeldByCurrentThread();
    // assert last.next == null;
    last = last.next = node;
}


take():

从队列中获取元素,获取不到,将阻塞

public E take() throws InterruptedException {
    E x;
    int c = -1;
   
    final AtomicInteger count = this.count;
    // 获取元素的锁
    final ReentrantLock takeLock = this.takeLock;
    // 获取可响应中断的锁
    takeLock.lockInterruptibly();
    try {
        // 如果没有元素,则当前线程添加到notEmpty条件队列
        while (count.get() == 0) {
            notEmpty.await();
        }
        // 获取链表中的第一个元素,即head后面一个
        x = dequeue();
        c = count.getAndDecrement();
        if (c > 1)
            // c > 1 说明链表中有元素,唤醒notEmpty条件队列中的其他线程读取数据
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
    // 由于此时取了一个元素,因此相等说明还有一个位置可以存元素,唤醒put操作的等待线程
    if (c == capacity)
        signalNotFull();
    return x;
}

private E dequeue() {
    // assert takeLock.isHeldByCurrentThread();
    // assert head.item == null;
    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;
}
poll:

等待指定时间,如果没有元素直接返回null

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);
        }
        x = dequeue();
        c = count.getAndDecrement();
        if (c > 1)
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

peek:

返回链表第一个元素,即head后一个

不存在直接返回null

public E peek() {
    if (count.get() == 0)
        return null;
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        Node<E> first = head.next;
        if (first == null)
            return null;
        else
            return first.item;
    } finally {
        takeLock.unlock();
    }
}
remove

fullyLock加锁, 此次不允许添加,取出元素

public boolean remove(Object o) {
    if (o == null) return false;
    fullyLock();
    try {
        // trail 用来记录 p前一个节点
        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();
    }
}
// 删除p节点,同时将p前驱trail 和 p.next 连接
void unlink(Node<E> p, Node<E> trail) {
    // assert isFullyLocked();
    // p.next is not changed, to allow iterators that are
    // traversing p to maintain their weak-consistency guarantee.
    p.item = null;
    trail.next = p.next;
    if (last == p)
        last = trail;
    if (count.getAndDecrement() == capacity)
        notFull.signal();
}

void fullyLock() {
    putLock.lock();
    takeLock.lock();
}

/**
     * Unlocks to allow both puts and takes.
     */
void fullyUnlock() {
    takeLock.unlock();
    putLock.unlock();
}
Itr

遍历过程几乎不会受到其他线程的影响

遍历过程中,不管是其他线程弹出元素还是执行Itr.remove(), 遍历都不会受到影响

private class Itr implements Iterator<E> {

	// 基于弱一致性的迭代器
    // 记录当前遍历到的节点
    private Node<E> current;
    // 记录current前一个节点
    private Node<E> lastRet;
    // 记录当前遍历的节点元素值
    private E currentElement;

    Itr() {
        fullyLock();
        try {
            current = head.next;
            if (current != null)
                currentElement = current.item;
        } finally {
            fullyUnlock();
        }
    }

    public boolean hasNext() {
        return current != null;
    }

   
    private Node<E> nextNode(Node<E> p) {
        for (;;) {
            Node<E> s = p.next;
            // 如果s == p, 说明遍历过程中,s节点刚好被弹出(take),返回head.next
            // take方法弹出元素时,会将p.next 指向 p
            // 只有开始才会出现,因为弹出的元素始终是头结点
            if (s == p)
                return head.next;
            // s == null : 可能遍历到最后一个
            // s.item != null: s 不为null
            if (s == null || s.item != null)
                return s;
            // 说明s != p, 且s != null && s.item == null,
            // 可能是由于s被Itr中的remove
            p = s;
        }
    }

    public E next() {
        fullyLock();
        try {
            if (current == null)
                throw new NoSuchElementException();
            // 记录当前元素值
            E x = currentElement;
            // 将当前元素赋给lastRet
            lastRet = current;
            // current移动到下一位置
            current = nextNode(current);
            // currentElement重新赋值
            currentElement = (current == null) ? null : current.item;
            return x;
        } finally {
            fullyUnlock();
        }
    }
	// 移除元素
    public void remove() {
        if (lastRet == null)
            throw new IllegalStateException();
        fullyLock();
        try {
            // 记录lastRet
            Node<E> node = lastRet;
            lastRet = null;
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {
                // 找到了待移除的元素
                if (p == node) {
                   // 取消p节点
                    unlink(p, trail);
                    break;
                }
            }
        } finally {
            fullyUnlock();
        }
    }
}
// 将p节点从链表中删除,让p的前驱trail指向p.next, 但是p的next不会重新赋null,保证了遍历过程正常执行
void unlink(Node<E> p, Node<E> trail) {
    // assert isFullyLocked();
    // p.next is not changed, to allow iterators that are
    // traversing p to maintain their weak-consistency guarantee.
    p.item = null;
    trail.next = p.next;
    if (last == p)
        last = trail;
    if (count.getAndDecrement() == capacity)
        notFull.signal();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值