并发阻塞队列LinkedBlockingQueue

1. 继承关系

public class LinkedBlockingQueue extends AbstractQueue
implements BlockingQueue, java.io.Serializable
实现了BlockingQueue,是一个利用链表实现的有界阻塞同步队列。可自定义队列容量,默认初始容量为Integer.MAX_VALUE

2. 实现的基本思想

是基于“two lock queue”算法的一个变体。利用两把锁(takeLock,和putLock),分别对读和写操作进行加锁,这样相比用一把锁的效率更高,用一把锁的时候读和写不能同时进行。同时使用两个condition,分别对队列进行阻塞和唤醒操作。

3. 具体实现

3.1 基础数据结构-链表和类常量

static class Node<E> {
        E item;

        /**
         * One of:
         * - the real successor Node
         * - this Node, meaning the successor is head.next
         * - null, meaning there is no successor (this is the last node)
         */
        Node<E> next;

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

Node是链表结构,item用于存储数据,next指向下一个节点的引用。

 /** The capacity bound, or Integer.MAX_VALUE if none */
    //容量,上线是Integer.MAX_VALUE
    private final int capacity;

    /** Current number of elements */
    //队列中当前的元素的总数
    private final AtomicInteger count = new AtomicInteger();

    /**
     * Head of linked list.
     * Invariant: head.item == null
     */
    //头节点,总是null,不存放数据,用于标识读的起始位置
    transient Node<E> head;

    /**
     * Tail of linked list.
     * Invariant: last.next == null
     */
    //尾节点,尾节点的next总是为空 last.next == null
    private transient Node<E> last;

    /** Lock held by take, poll, etc */
    //针对take, poll方法的锁
    private final ReentrantLock takeLock = new ReentrantLock();

    /** Wait queue for waiting takes */
    //不为空条件,当notEmpty.await被调用时,说明队列为空。notEmpty.signal
    //调用时说明队列不为空,可以继续取数据
    private final Condition notEmpty = takeLock.newCondition();

    /** Lock held by put, offer, etc */
    //作用与takeLock相反
    private final ReentrantLock putLock = new ReentrantLock();

    /** Wait queue for waiting puts */
    //当notFull.await被调用时,说明队列已经饱和,当notFull.signal
    //调用时说明队列还没达到最大容量,可以继续存放数据
    private final Condition notFull = putLock.newCondition();

从上面的定义我们看到所有的变量都是finl类型,由于两把锁操作队列,那么队列的容量计数上可能存在并发问题,在这里使用AtomicInteger计数避免了该问题。

3.2 构造方法

构造方法有3个,一个无参的构造方法,一个带有初始容量的构造方法,一个带有初始数据的构造方法

    //无参的构造方法默认容量为(Integer.MAX_VALUE
    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);
        /** 为什么要在初始化的时候加锁呢,因为java的构造方法并不是线程安全的.当我们new一个对象的时候先分配对象的内存,然后再初始化对象,在对象初始化之前,它的引用可能已经暴露给其它线程,这样其它线程就能进行写入操作.不加读锁是因为读的方法先会判断元素是否为空,初始的时候默认为空不会造成并发问题.个人愚见,如有其它想法欢迎留言讨论
        */
        final ReentrantLock putLock = this.putLock;
        putLock.lock(); // Never contended, but necessary for visibility
        try {
            int n = 0;
            for (E e : c) {
                //由此可见该队列不能存放null类型的元素,因为头结点始终为null
                if (e == null)
                    throw new NullPointerException();
                if (n == capacity)
                    throw new IllegalStateException("Queue full");
                //依次进队
                enqueue(new Node<E>(e));
                ++n;
            }
            //注意set方法可能会存在并发问题,但在该队列中只有此处和序列化的时候调用,因此不会存在并发问题。真的是到处都存在实现的细节啊!
            count.set(n);
        } finally {
            putLock.unlock();
        }
    }
    
    //进队方法,在初始化的时候头尾节点都被指向为同一个空节点,last.next = node,将该元素放到原为节点的下一个元素,last=node,将尾节点从新指向该节点
    private void enqueue(Node<E> node) {
        // assert putLock.isHeldByCurrentThread();
        // assert last.next == null;
        last = last.next = node;
    }

3.3 插入操作

阻塞队列的put操作和take操作有一个共同特点就是,如果获取不到元素或者不能插入元素则无限期等待。
看看put是怎么实现的

public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        // Note: convention in all put/take/etc is to preset local var
        // holding count negative to indicate failure unless set.
        int c = -1;
        Node<E> node = new Node<E>(e);
        final ReentrantLock putLock = this.putLock;
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly();
        try {
            //如果已经达到最大容量,则notFull条件被await,等待队列不为空
            while (count.get() == capacity) {
                notFull.await();
            }
            //将node加入链表
            enqueue(node);
            c = count.getAndIncrement();
            //当前插入的元素+原来的总数<capacity,说明还没达到最大容量,如果有阻塞的写线程则唤醒被阻塞的写线程
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            //释放锁
            putLock.unlock();
        }
        //如果原数据总数为0,则唤醒被阻塞的读线程,去读取最新放入的元素
        if (c == 0)
            signalNotEmpty();
    }
    
    //获得写锁,然后进行唤醒被await()的读线程
    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
    }

put方法如上面所示,在写入的时候获取写锁,判断能否写入,如能写入,则将元素插到队尾,同时判断插入后队列是否满,未满则唤醒被await()的写线程,并且判断原数据总数为是否为0,为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) {
                if (nanos <= 0)
                    return false;
                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;
    }
    
    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();
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }

offer和put类似,只不过off不会一直等待而是返回特殊的值。接下来看看获取操作

3.4 读取操作

    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();
            //获取当前的队列元素并减1
            c = count.getAndDecrement();
            //如果c>1表示当前元素出队后还有剩余元素,唤醒其它被阻塞的获取线程
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        //为什么c==capacity才能唤醒等待插入的线程呢,因为c = count.getAndDecrement()先获取当前总数再减1,
        //如果c==capacity,在本次take成功后实际的count=capacity-1,刚刚好有剩余的空间等待插入
        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;
        //替换头节点,将头结点的下一个节点设置为null,因为头结点始终是null
        h.next = h; // help GC
        //将头节点设置为原头结点的下一个节点
        head = first;
        //取出原头结点的下一个节点(此刻已经是头结点了)的数据
        E x = first.item;
        //将原头结点的下一个节点(此刻已经是头结点了)的数据设置为null,满足头节点始终是null
        first.item = null;
        //返回取出的数据
        return x;
    }
    

如果没有元素take操作会一直阻塞,当队列不为空还需要唤醒其它的被阻塞的取线程,当队列是满的时候take完后还需要唤醒被阻塞的写线程。
poll操作提供一个超时和不超时的方法,与offer类似

    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) {
                //超时后返回null
                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();
        //如果没能进上面的if语句,则x此时为null
        return x;
    }

poll当获取不到或者超时返回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();
        }
    }

peek操作很简单只返回数据不做移除操作。

3.5 移除操作

我们知道链表的移出需要先找到需要移出的元素,然后更改元素的next指向,最坏的情况需要遍历整个链表。此时任何取线程或者读线程都会更改链表的结构,这样会对链表的遍历造成影响,所以需要同时加写锁和读锁

    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)) {
                    //移出元素,注意trail是p的前一个元素
                    unlink(p, trail);
                    return true;
                }
            }
            return false;
        } finally {
            //释放读锁和写锁
            fullyUnlock();
        }
    }
    //获取写锁和读锁
    void fullyLock() {
        putLock.lock();
        takeLock.lock();
    }
    //释放读锁和写锁
    void fullyUnlock() {
        takeLock.unlock();
        putLock.unlock();
    }
    //移出元素
    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设置为null
        p.item = null;
        //将p的前一个节点trail的后继节点设置为p的后继节点,断开p节点
        trail.next = p.next;
        //如果p是最后一个节点,那么将last设置为trail
        if (last == p)
            last = trail;
        //这行代码与take方法里面的signalNotFull()同理,如果移出p的当前队列是满的话,移出后刚好有剩余的空间可以写入,所以此时唤醒等待写的线程
        if (count.getAndDecrement() == capacity)
            notFull.signal();
    }

由于contains操作也会遍历整个链表,写操作和取操作都会对链表的遍历造成影响,需要同时加读锁和写锁

public boolean contains(Object o) {
        if (o == null) return false;
        fullyLock();
        try {
            for (Node<E> p = head.next; p != null; p = p.next)
                if (o.equals(p.item))
                    return true;
            return false;
        } finally {
            fullyUnlock();
        }
    }

到此LinkedBlockingQueue的主要方法都将完了。将LinkedBlockingQueue和ArrayBlockingQueue对比一下:

  • 1、两者的数据结构不同,LinkedBlockingQueue使用链表结构,ArrayBlockingQueue使用数组结构
  • 2、锁的粒度不同LinkedBlockingQueue使用两把锁,读和写操作互不影响。ArrayBlockingQueue使用一把锁,读和写操作都会锁住整个数组
  • 3、都是用ReentrantLock和Condition实现并发阻塞功能
  • 4、都是FIFO(先进先出)原则对元素进行排序。队列的头部 是在队列中存在时间最长的元素。队列的尾部 是在队列中存在时间最短的元素
  • 5、单就性能而言LinkedBlockingQueue吞吐量通常要高于ArrayBlockingQueue
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值