LinkedBlockingQueue源码分析

LinkedBlockingQueue

list

public class LinkedBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
1. 静态内部类 Node

  链表节点类,对象(任务)入队列时会将对象封装到Node中并挂载到链表尾部;出队列操作会取下链表头部节点并获取其中的item变量。

    static class Node<E> {
        E item; // 用于存放出入队列的对象
        Node<E> next; // 指向下一个节点的指针

        Node(E x) { item = x; }
    }
2. 使用变量
  • Condition 对象简介:
      Condition是在java 1.5中才出现的,它用来替代传统的Object的wait()、notify()实现线程间的协作,相比使用Object的wait()、notify(),使用Condition的await()、signal()这种方式实现线程间协作更加安全和高效。
      Condition是个接口,基本的方法就是await()和signal()方法;Condition依赖于Lock接口,生成一个Condition的基本代码是lock.newCondition();调用Condition的await()和signal()方法,都必须在lock保护之内,就是说必须在lock.lock()和lock.unlock之间才可以使用。
      Conditon中的await()对应Object的wait();Condition中的signal()对应Object的notify();Condition中的signalAll()对应Object的notifyAll()。
    引用自:https://blog.csdn.net/a1439775520/article/details/98471610
    private final int capacity; // 若实现为有界队列,保存容量上限,以便在对象数达到上限时引发写阻塞
    private final AtomicInteger count = new AtomicInteger(); // 当前任务数,使用原子类保证线程安全
    transient Node<E> head; // 头索引节点指针,指向队列头索引节点,一般为 null
    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(); // 由写阻塞锁获取线程通信类
3. 底层调用方法
  • signalNotEmpty()& signalNotFull():用于在队列非空(满)时唤醒读(写)阻塞的线程
      在出入队列方法的尾部通过当前对象数为0或容量上限来判断队列为满(空),进而得知当前有线程陷入阻塞,并调用这两个方法唤醒线程。此处容易让人疑惑,实际上在读(写)操作后队列肯定不为满(空),直接调用 signalNotEmpty()signalNotFull()来唤醒线程即可,那么结尾处的判断有何作用呢?
      实际上这是处于对性能的考量:因为如果之前的队列本身就不为空,则说明没有处于因notEmpty.wait()而阻塞的读线程,自然也就无需进行唤醒动作,写线程同理。
    引用自:https://blog.csdn.net/qq_26898645/article/details/95446943

  • enqueue(Node<E> node):通过获取头节点并后移头索引指针的方式使对象出队列
    enqueue

  • dequeue():通过在链表尾部插入节点的方式使对象入队列
    dequeue

  • fullyLock() & fullyUnlock():同时对读写阻塞锁加锁(解锁),以保证加锁顺序一致,防止出现锁顺序死锁

    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock(); // 获取锁,因为Condition对象需要在加锁情况下才能使用
        try {
            notEmpty.signal(); // 唤醒读阻塞的线程
        } finally {
            takeLock.unlock(); // 释放锁
        }
    }
    private void signalNotFull() {
        final ReentrantLock putLock = this.putLock;
        putLock.lock(); // 获取锁,因为Condition对象需要在加锁情况下才能使用
        try {
            notFull.signal(); // 唤醒写阻塞的线程
        } finally {
            putLock.unlock(); // 释放锁
        }
    }
    private void enqueue(Node<E> node) {
        // 断言当前线程已获取锁并且last节点的下一个节点为 null
        last = last.next = node; // 将node加入队列尾并更新队列尾节点
    }
    private E dequeue() {
        // 断言当前线程以获取锁并且head节点为 null
        Node<E> h = head; // 获取头索引节点
        Node<E> first = h.next; // 获取头索引节点指向的队列头节点
        h.next = h; // 头索引节点指针后移一位,使旧的索引节点被垃圾回收
        head = first; // 更新头索引节点指针
        E x = first.item; // 获取对象
        first.item = null; // 将当前的头索引节点置为 null
        return x;
    }
    void fullyLock() {
        putLock.lock(); // 先加写阻塞锁
        takeLock.lock(); // 后加读阻塞锁
    }

    void fullyUnlock() {
        takeLock.unlock(); // 先对写阻塞锁解锁
        putLock.unlock(); // 后对读阻塞锁解锁
    }
4. 构造方法
  • LinkedBlockingQueue():默认构造无界队列,即队列容量为 Integer.MAX_VALUE
  • LinkedBlockingQueue(int capacity):构造有界队列,上界为 capacity
  • LinkedBlockingQueue(Collection<? extends E> c):构造有界队列,并将集合中的对象加入队列
    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(); // 当集合中存在 null 对象时,抛出空指针异常
                if (n == capacity)
                    throw new IllegalStateException("Queue full"); // 当队列达到上限时,抛出非法状态异常
                enqueue(new Node<E>(e)); // 将集合内的元素加入队列
                ++n; // 统计加入队列的对象数目
            }
            count.set(n); // 将对象数保存到 count 原子类中
        } finally {
            putLock.unlock();
        }
    }
5. 入队列方法
  • put(E e):在阻塞时触发wait使线程等待,适用于并发量较小的情形
  • offer(E e, long timeout, TimeUnit unit):会在超时后直接false,适用于并发量较大的情形
  • offer(E e):若队列满直接false,适用于并发量极大的情形
    public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException(); // 不能插入 null(因为null被用于识别链表的头尾节点)
        int c = -1;
        Node<E> node = new Node<E>(e); // 将对象封装入Node节点中
        final ReentrantLock putLock = this.putLock; // 获取写阻塞锁
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly(); // 加锁,可被中断
        try {
            while (count.get() == capacity) { // 当队列满时,线程 wait 进入写阻塞
                notFull.await();
            }
            enqueue(node); // 当队列不满,将节点添加到队列尾部
            c = count.getAndIncrement(); // 使用原子类的CAS操作更新对象数目
            if (c + 1 < capacity) // 若队列再写入对象使对象数目达到c+1后队列仍未满,唤醒写阻塞线程继续写入
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0) // 若当前队列为空,说明有读线程陷入阻塞,唤醒阻塞的读线程
            signalNotEmpty();
    }
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {

        if (e == null) throw new NullPointerException(); // 不能插入 null
        long nanos = unit.toNanos(timeout); // 获取 nano 时间
        int c = -1;
        final ReentrantLock putLock = this.putLock; // 获取写阻塞锁
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly(); // 加锁,可中断
        try {
            while (count.get() == capacity) { 
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos); // 若队列满,定时等待,若超时则 false
            }
            enqueue(new Node<E>(e)); // 若队列不满,将对象加入队列
            c = count.getAndIncrement(); // 更新当前队列中的对象数目
            if (c + 1 < capacity) // 若队列再写入对象使对象数目达到c+1后队列仍未满,唤醒写阻塞线程继续写入
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0) // 若当前队列为空,说明有读线程陷入阻塞,唤醒阻塞的读线程
            signalNotEmpty();
        return true;
    }
    public boolean offer(E e) {
        if (e == null) throw new NullPointerException(); // 不能插入 null
        final AtomicInteger count = this.count; // 获取当前对象数目
        if (count.get() == capacity)
            return false;
        int c = -1;
        Node<E> node = new Node<E>(e); // 将对象封装入节点
        final ReentrantLock putLock = this.putLock; // 获取写阻塞锁
        putLock.lock();
        try {
            if (count.get() < capacity) { // 若队列不满,将对象加入队列尾部
                enqueue(node);
                c = count.getAndIncrement(); // 更新队列中当前对象数目(注意,只有队列不满时c才会被重新赋值)
                if (c + 1 < capacity) // 若队列再写入对象使对象数目达到c+1后队列仍未满,唤醒写阻塞线程继续写入
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        if (c == 0) // 若当前队列为空,说明有读线程陷入阻塞,唤醒阻塞的读线程
            signalNotEmpty();
        return c >= 0; // 若队列满 c未被重新赋值,依旧为 -1,返回 false,否则返回 true
    }
6. 出队列方法
  • take():在阻塞时触发wait使线程等待,适用于并发量较小的情形
  • poll(long timeout, TimeUnit unit):会在超时后直接 null ,适用于并发量较大的情形
  • poll():若队列空直接返回 null ,适用于并发量极大的情形
    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) { // 若队列空,线程 wait 进入读阻塞
                notEmpty.await();
            }
            x = dequeue(); // 取出队列头对象
            c = count.getAndDecrement(); // 更新队列中当前的对象数目
            if (c > 1) // 若再次读取后对象数目为c-1依然不为空,唤醒读阻塞线程继续读取
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity) // 若当前队列满,说明有写线程陷入阻塞,唤醒阻塞的写线程
            signalNotFull();
        return x;
    }
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        E x = null;
        int c = -1;
        long nanos = unit.toNanos(timeout); // 获取 nano 时间
        final AtomicInteger count = this.count; // 获取队列当前的对象数量
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) { // 当队列空时,定时等待,超时后返回 null
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            x = dequeue(); // 若队列非空,取出队列头的对象
            c = count.getAndDecrement(); // 更新队列中当前的对象数目
            if (c > 1) // 若再次读取后对象数目为c-1依然不为空,唤醒读阻塞线程继续读取
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity) // 若当前队列满,说明有写线程陷入阻塞,唤醒阻塞的写线程
            signalNotFull();
        return x;
    }

  poll()使用双重检查加锁机制(DCL),避免频繁获取锁对象,懒汉式单例模式也可使用双重检查加锁。在此处由于count为原子类,保证了其可见性,如果是在单例模式构造中,必须要使用volatile变量来保证可见性。
详情见:https://blog.csdn.net/WK_SDU/article/details/82464846

    public E poll() {
        final AtomicInteger count = this.count; // 获取队列当前的对象数目
        if (count.get() == 0) // 若队列为空,直接返回 null(由于无阻塞操作,因此无需加锁,避免频繁获取锁)
            return null;
        E x = null;
        int c = -1;
        final ReentrantLock takeLock = this.takeLock; // 若队列不为空,需要取出对象,因此必须加锁
        takeLock.lock();
        try {
            if (count.get() > 0) { // 再次检查队列若不为空,取出队列头对象
                x = dequeue();
                c = count.getAndDecrement(); // 更新当前队列的对象数目
                if (c > 1) // 若再次读取后对象数目为c-1依然不为空,唤醒读阻塞线程继续读取
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == capacity) // 若当前队列满,说明有写线程陷入阻塞,唤醒阻塞的写线程
            signalNotFull();
        return x;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值