JUC队列-LinkedBlockingQueue(二)

LinkedBlockingQueue介绍

LinkedBlockingQueue是一个以单向链表实现的阻塞队列,链表队列的吞吐量通常高于基于数组的队列,但是在大多数场景中,其可预见的性能要低。

要注意的是,LinkedBlockingQueue可选容量,防止膨胀,默认大小为Integer.MAX_VALUE。

LinkedBlockingQueue的UML图:

  1. LinkedBlockingQueue继承于AbstractQueue,它本质上是一个FIFO(先进先出)的队列。
  2. LinkedBlockingQueue实现了BlockingQueue接口,它支持多线程并发。当多线程竞争同一个资源时,某线程获取到该资源之后,其它线程需要阻塞等待。
  3. LinkedBlockingQueue是通过单链表实现的。
    • head是链表的表头。取出数据时,都是从表头head处插入。
    • last是链表的表尾。新增数据时,都是从表尾last处插入。
    • count是链表的实际大小,即当前链表中包含的节点个数。
    • capacity是列表的容量,它是在创建链表时指定的。
    • putLock是插入锁,takeLock是取出锁;notEmpty是“非空条件”,notFull是“未满条件”。通过它们对链表进行并发控制。

LinkedBlockingQueue在实现“多线程对竞争资源的互斥访问”时,对于“插入”和“取出(删除)”操作分别使用了不同的锁。对于插入操作,通过“插入锁putLock”进行同步;对于取出操作,通过“取出锁takeLock”进行同步。

此外,插入锁putLock和“非满条件notFull”相关联,取出锁takeLock和“非空条件notEmpty”相关联。通过notFull和notEmpty更细腻的控制锁。

LinkedBlockingQueued的源码分析

构造方法

public LinkedBlockingQueue(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    this.capacity = capacity;
    last = head = new Node<E>(null);
}

其他静态初始化:

// 容量
private final int capacity;
// 当前数量
private final AtomicInteger count = new AtomicInteger(0);
private transient Node<E> head; // 链表的表头
private transient Node<E> last; // 链表的表尾
// 用于控制“删除元素”的互斥锁takeLock 和 锁对应的“非空条件”notEmpty
private final ReentrantLock takeLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition();
// 用于控制“添加元素”的互斥锁putLock 和 锁对应的“非满条件”notFull
private final ReentrantLock putLock = new ReentrantLock();
private final Condition notFull = putLock.newCondition();

添加元素

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 {
              //如果队列已经满了则await
            while (count.get() == capacity) {
                notFull.await();
            }
            //不满则插入结点
            enqueue(node);
            c = count.getAndIncrement();
            // 如果在插入元素之后,队列仍然未满,则唤醒notFull上的等待线程。
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        // 如果在插入节点前,队列为空;则插入节点后,唤醒notEmpty上的等待线程
        if (c == 0)
            signalNotEmpty();
    }

enqueue()方法很简单:

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

取出元素

public E take() throws InterruptedException {
    E x;
    int c = -1;
    final AtomicInteger count = this.count;
    final ReentrantLock takeLock = this.takeLock;
    // 获取“取出锁”,若当前线程是中断状态,则抛出InterruptedException异常
    takeLock.lockInterruptibly();
    try {
        // 若“队列为空”,则一直等待。
        while (count.get() == 0) {
            notEmpty.await();
        }
        // 取出元素
        x = dequeue();
        // 取出元素之后,将“节点数量”-1;并返回“原始的节点数量”。
        c = count.getAndDecrement();
        if (c > 1)
            notEmpty.signal();
    } finally {
        // 释放“取出锁”
        takeLock.unlock();
    }
    // 如果在“取出元素之前”,队列是满的;则在取出元素之后,唤醒notFull上的等待线程。
    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;
}

总结:
ArrayBlockingQueue和LinkedBlockingQueue有很多相似的地方,他们的不同点在于:

他们都是阻塞队列,但ArrayBlockingQueue是数组实现的,并且是有界限的;而LinkedBlockingQueue是链表实现的,是无界限的,而且ArrayBlockingQueue只用了一个独占锁,而LinkedBlockingQueue用了两个独占锁,所以ArrayBlockingQueue没有实现读写分离,而LinkedBlockingQueue可以。

为什么要这么设计呢?

LinkedBlockingQueue的较大一部分时间需要构造节点,导致较长的等待,所以同时存取有较大优化,而ArrayBlockingQueue的不用构造节点,加锁和解锁的时间可能占比较大。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值