LinkedBlockingQueue源码

目录

介绍

数据结构

链表节点

属性

方法实现

offer

poll

peek

put

take

enqueue,dequeue

signal

fullLock

注意

参考


介绍

java.util.concurrent.LinkedBlockingQueue 是一个基于单向链表的、范围任意的(其实是有界的)、FIFO 阻塞队列。访问与移除操作是在队头进行,添加操作是在队尾进行,并分别使用不同的锁进行保护,只有在可能涉及多个节点的操作才同时对两个锁进行加锁

由于同时使用了两把锁,在需要同时使用两把锁时,加锁顺序与释放顺序是非常重要的:必须以固定的顺序进行加锁,再以与加锁顺序的相反的顺序释放锁。锁使用了ReentrantLock,参考:ReentrantLock源码

头结点和尾结点一开始总是指向一个哨兵的结点,它不持有实际数据,当队列中有数据时,头结点仍然指向这个哨兵,尾结点指向有效数据的最后一个结点。这样做的好处在于,与计数器 count 结合后,对队头、队尾的访问可以独立进行,而不需要判断头结点与尾结点的关系。

数据结构

链表节点

    static class Node<E> {
        E item;

        /**
         * 后继指针。值为下列之一:
         * 实际的后继结点。
         * 自身,表示后继是 head.next (用于在遍历处理时判断)
         * null,表示没有后继(这是尾结点)
         */
        Node<E> next;

        Node(E x) { item = x; }
    }

属性

// 最大容量上限,默认是 Integer.MAX_VALUE
private final int capacity;

// 当前元素数量,这是个原子类。因为读写分别使用不同的锁,但都会访问这个属性,所以它需要是线程安全的。
private final AtomicInteger count = new AtomicInteger(0);

// 头结点
private 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();

方法实现

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<E> node = new Node<E>(e);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            if (count.get() < capacity) {
                //节点入队列
                enqueue(node);
                c = count.getAndIncrement();
                //队列未满,则唤醒其他put线程
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }

        /*当c=0时,即意味着之前的队列是空队列,出队列的线程都处于等待状态,
        现在新添加了一个新的元素,即队列不再为空,因此它会唤醒正在等待获取元素的线程。
        */
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }
    
    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) {
                //超时,则返回false。
                if (nanos <= 0)
                    return false;
                //否则继续等待notFull
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(new Node<E>(e));
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return true;
    }

poll


    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;
    }

    public E poll() {
        final AtomicInteger count = this.count;
        if (count.get() == 0)
            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)
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }

peek

    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();
        }
    }

put

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();

    // 在所有的 put/take/etc 等操作中预设值本地变量 c 为负数表示失败。成功会设置为 >= 0 的值。
    int c = -1;
    Node<E> node = new Node(e);

    // 下面两行是访问优化
    final ReentrantLock putLock = this.putLock;
    final AtomicInteger count = this.count;

    putLock.lockInterruptibly();
    try {
        /*
         * 注意,count用于等待监视,即使它没有用锁保护。这个可行是因为
         * count 只能在此刻(持有putLock)减小(其他put线程都被锁拒之门外),
         * 当count对capacity发生变化时,当前线程(或其他put等待线程)将被通知。
         * 在其他等待监视的使用中也类似。
         */
        while (count.get() == capacity) {
            notFull.await();
        }

        enqueue(node);
        c = count.getAndIncrement();

        // 还有可添加空间则唤醒put等待线程。
        if (c + 1 < capacity)
            notFull.signal();
    } finally {
        putLock.unlock();
    }

        /*当c=0时,即意味着之前的队列是空队列,出队列的线程都处于等待状态,
        现在新添加了一个新的元素,即队列不再为空,因此它会唤醒正在等待获取元素的线程。
        */
    if (c == 0)
        signalNotEmpty();
}

take

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)
            notEmpty.signal();
    } finally {
        takeLock.unlock();
    }

    // 注意,c 是调用 getAndDecrement 返回的,如果 if 成立,
    // 表明前面的 count == capacity ,有put线程在等待,可以添加新元素,所以唤醒 添加线程。
    if (c == capacity)
        signalNotFull();
    return x;
}

enqueue,dequeue

public LinkedBlockingQueue(int capacity) {
    if (capacity <= 0) throw new IllegalArgumentException();
    this.capacity = capacity;
    //head,last都指向哨兵节点
    last = head = new Node<E>(null);
}

// 在持有 putLock 锁下执行
private void enqueue(Node<E> node) {
    // assert putLock.isHeldByCurrentThread();
    // assert last.next == null;
    //把node作为最后一个节点,更新last.next引用
    last = last.next = node;
}


// 在持有 takeLock 锁下执行
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;
}

signal

    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
    }

    private void signalNotFull() {
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            notFull.signal();
        } finally {
            putLock.unlock();
        }
    }

fullLock

有些方法必须同时获取take与put锁

在需要同时使用两把锁时,加锁顺序与释放顺序是非常重要的:必须以固定的顺序进行加锁,再以与加锁顺序的相反的顺序释放锁。

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

    void fullyUnlock() {
        takeLock.unlock();
        putLock.unlock();
    }

    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();
        }
    }

    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();
    }

注意

  • 为什么每次put()后总要唤醒其他put线程或者take()后要唤醒其他take线程

因为signalNotEmpty(),signalNotFull()方法仅唤醒一个线程,如果有多个等待线程,就会导致剩余线程一直挂起。

  • 为什么signalNotEmpty(),signalNotFull()不唤醒多个线程

假设此时仅有1个空间,唤醒N个put线程后,仅有一个take线程会执行put操作,其他N-1个线程刚被唤醒,又要挂起,影响性能

 

参考

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值