深度解析并发阻塞队列

上篇博客中我们说到了线程池中的workQueue,任务队列

private final BlockingQueue<Runnable> workQueue;
复制代码

可以看到是BlockingQueue类型,BlockingQueue是个接口,我们实际上用到的并发队列是BlockingQueue的各种实现。我们就挨个儿来一探究竟吧

BlockingQueue

public interface BlockingQueue<E> extends Queue<E> {}
复制代码

BlockingQueue继承自Queue,所以满足先进先出。源码前边还有一大堆介绍BlockingQueue,总结下来就是BlockingQueue对插入操作、移除操作、获取元素操作提供了四种不同的方法用于不同的场景中使用:1、抛出异常;2、返回特殊值(null 或 true/false,取决于具体的操作);3、阻塞等待此操作,直到这个操作成功;4、阻塞等待此操作,直到成功或者超时指定时间

BlockingQueue 不接受 null 值的插入

BlockingQueue 是设计用来实现生产者-消费者队列的。

BlockingQueue 的实现都是线程安全的,但是批量的集合操作如 addAll, containsAll, retainAll 和 removeAll 不一定是原子操作。如 addAll(c) 有可能在添加了一些元素后中途抛出异常,此时 BlockingQueue 中已经添加了部分元素,这个是允许的,取决于具体的实现。

好了,这只是个接口,我们不多废话了,赶紧去看实现吧

ArrayBlockingQueue

顾名思义,它底层实现就是数组

// 用于存放元素的数组
final Object[] items;

// 下一次读取操作的位置
int takeIndex;

// 下一次写入操作的位置
int putIndex;

// 队列中元素数量
int count;

// 锁保证出入队原子性
final ReentrantLock lock;

// 出队同步,等待满足非空
private final Condition notEmpty;

// 入队同步,等待满足非满
private final Condition notFull;
复制代码

构造函数

public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }
    
public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }
复制代码

可以看到,默认是使用ReentrantLock的非公平锁。

offer

public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
}

private void enqueue(E x) {
       
        final Object[] items = this.items;
        
        // 元素入队
        items[putIndex] = x;
        // putIndex达到最大,调整
        if (++putIndex == items.length)
            // 队列前边的已被取走,所以putIndex达到最大可以再从0开始
            putIndex = 0;
        count++;
        // 此时满足非空,可以唤醒一个notEmpty等待队列上的元素
        notEmpty.signal();
}
复制代码
  1. 保证元素非空
  2. 获得锁
  3. 如果队列满了,返回false,添加失败;否则,添加成功,返回true
  4. 释放锁,前边说过释放锁的语义,把修改的共享变量值刷回主内存

注意队列满是元素个数等于count,而非使用put/takeindex判断

put

public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                // 不满足非满,等待
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
复制代码

没啥好说的,如果队列满了就阻塞挂起在notFull条件队列上

poll

public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
}

private E dequeue() {
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        // 此时取走一个元素,可以唤醒notFull上的一个线程    
        notFull.signal();
        return x;
}
复制代码

可以看到无非就是拿锁,然后取走元素,更新takeIndex,唤醒botFull,最后释放锁。

take

public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
复制代码

相比poll,take中队列是空时会阻塞挂起,poll则没有阻塞直接返回null

peek

public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex); 
        } finally {
            lock.unlock();
        }
}

final E itemAt(int i) {
        return (E) items[i];
    }
复制代码

同样peek也没有阻塞,直接返回队列头部元素;空的话返回null

size

public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return count;
        } finally {
            lock.unlock();
        }
    }
复制代码

获得锁,返回count,释放锁

ArrayBlockingQueue总结

ArrayBlockingQueue中只有take和put是阻塞的,其他方法都是直接返回,同时可以看到ArrayBlockingQueue中的lock是一个粒度很大的全局锁,每个操作方法都需要先获得锁,类似于hashtable的synchronized,不过也因为此,这里的size统计很精准

LinkedBlockingQueue

还是顾名思义,它的底层是链表

属性

private final int capacity;

    // 队列中元素数量
    private final AtomicInteger count = new AtomicInteger();

    // 链表头
    transient Node<E> head;

    // 链表尾
    private transient Node<E> last;

    //  take,poll, peek 等读操作的方法需要获取到这个锁
    private final ReentrantLock takeLock = new ReentrantLock();

    // 等非空条件满足的condition
    private final Condition notEmpty = takeLock.newCondition();

    // put, offer 等写操作的方法需要获取到这个锁
    private final ReentrantLock putLock = new ReentrantLock();

    // 等不满条件满足的condition
    private final Condition notFull = putLock.newCondition();
复制代码

我们可以看到有写锁和读锁,所以写操作之间和读操作之间是不会有并发问题的,那么写读之间呢?我们底下介绍

构造方法

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);
}
复制代码

构造函数中初始化了一个头节点,那么第一个元素入队的时候,队列中就会有两个元素。读取元素时,也总是获取头节点后面的一个节点。count 的计数值不包括这个头节点。

put

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 {
            // 如果队列满了,等待notFull条件满足
            while (count.get() == capacity) {
                notFull.await();
            }
            // 满足notFull,新增节点入队
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                // 如果此时仍然没满,唤醒等待在notFull上的一个线程
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            // c==0即元素入队前是空的,那么所有的读线程都在等待 notEmpty 这个条件,等待唤醒,这里做一次唤醒操作
            signalNotEmpty();
}

private void enqueue(Node<E> node) {
        // 让last指向新增元素,注意是在获取锁的情况下进行的,不存在并发问题
        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 {
            while (count.get() == 0) {
                notEmpty.await();
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        c==capacity的话,此时去走一个,就可以唤醒阻塞在notFull上的线程了
        if (c == capacity)
            signalNotFull();
        return x;
}


// 这里直接把头节点置null,且指向自己,头节点的next值为null,变为新的头节点
private E dequeue() {
        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;
}
复制代码

如果队列空则等待非空,满足条件取出队列头

size

public int size() {
        return count.get();
}
复制代码

这里的count并不是很准确。

其他方法大同小异,都是不再阻塞

LinkedBlockingQueue总结

LinkedBlockingQueue内部通过单链表实现,使用头尾节点进行入队和出队操作,分别采用两把锁,所以出队和入队可以同时进行的。

SynchronousQueue

继续顾名思义,同步队列,何谓同步?这里指的是当一个线程往队列中写入一个元素时,写入操作不会立即返回,需要等待另一个线程来将这个元素拿走;同理,当一个读线程做读操作的时候,同样需要一个相匹配的写线程的写操作。这里的 Synchronous 指的就是读线程和写线程需要同步,一个读线程匹配一个写线程。

所以说这个队列其实不存在,其不提供任何空间(一个都没有)来存储元素。数据必须从某个写线程交给某个读线程,而不是写到某个队列中等待被消费。

构造方法

public SynchronousQueue(boolean fair) {
        transferer = fair ? new TransferQueue<E>() : new TransferStack<E>();
    }
复制代码

可以看到其实就是初始化了一个transferer,可以猜到这里fair就是公平锁吧,如果公平锁就初始化TransferQueue,否则初始化TransferStack,至于这是个什么东西,一会儿再看。

老规矩,老看下put/take吧

put

// 写入值
public void put(E o) throws InterruptedException {
    if (o == null) throw new NullPointerException();
    if (transferer.transfer(o, false, 0) == null) { // 1
        Thread.interrupted();
        throw new InterruptedException();
    }
}
// 读取值并移除
public E take() throws InterruptedException {
    Object e = transferer.transfer(null, false, 0); // 2
    if (e != null)
        return (E)e;
    Thread.interrupted();
    throw new InterruptedException();
}
复制代码

put/take内部都是调用 Transferer.transfer(…) 方法,区别在于第一个参数是否为 null 值。

我们看到,写操作 put(E o) 和读操作 take() 都是调用 Transferer.transfer(…) 方法,区别在于第一个参数是否为 null 值。 我们来看看 transfer 的设计思路,其基本算法如下: 当调用这个方法时,如果队列是空的,或者队列中的节点和当前的线程操作类型一致(如当前操作是 put 操作,而队列中的元素也都是写线程)。这种情况下,将当前线程加入到等待队列即可。 如果队列中有等待节点,而且与当前操作可以匹配(如队列中都是读操作线程,当前线程是写操作线程,反之亦然)。这种情况下,匹配等待队列的队头,出队,返回相应数据。 其实这里有个隐含的条件被满足了,队列如果不为空,肯定都是同种类型的节点,要么都是读操作,要么都是写操作。这个就要看到底是读线程积压了,还是写线程积压了。 我们可以假设出一个男女配对的场景:一个男的过来,如果一个人都没有,那么他需要等待;如果发现有一堆男的在等待,那么他需要排到队列后面;如果发现是一堆女的在排队,那么他直接牵走队头的那个女的。

这块儿源代码就不介绍了,大家了解上边的东西就够了,因为本身这个队列用的也很少,只有线程池中会用到。

PriorityBlockingQueue

优先级队列,要实现优先级就涉及到比较大小,所以插入队列的对象必须是课比较大小的。同样不可插入null。

其实可以说他是无界队列,因为他的大小并不是固定,支持扩容操作,所以put方法不会阻塞

属性

// 构造方法中,如果不指定大小的话,默认大小为 11
private static final int DEFAULT_INITIAL_CAPACITY = 11;
// 数组的最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

// 这个就是存放数据的数组
private transient Object[] queue;

// 队列当前大小
private transient int size;

// 大小比较器,如果按照自然序排序,那么此属性可设置为 null
private transient Comparator<? super E> comparator;

// 并发控制所用的锁,所有的 public 且涉及到线程安全的方法,都必须先获取到这个锁
private final ReentrantLock lock;

private final Condition notEmpty;

// 这个也是用于锁,用于数组扩容的时候,需要先获取到这个锁,才能进行扩容操作
// 其使用 CAS 操作
private transient volatile int allocationSpinLock;
复制代码

构造方法

// 默认构造方法,采用默认值(11)来进行初始化
public PriorityBlockingQueue() {
    this(DEFAULT_INITIAL_CAPACITY, null);
}
// 指定数组的初始大小
public PriorityBlockingQueue(int initialCapacity) {
    this(initialCapacity, null);
}
// 指定比较器
public PriorityBlockingQueue(int initialCapacity,
                             Comparator<? super E> comparator) {
    if (initialCapacity < 1)
        throw new IllegalArgumentException();
    this.lock = new ReentrantLock();
    this.notEmpty = lock.newCondition();
    this.comparator = comparator;
    this.queue = new Object[initialCapacity];
}
复制代码

扩容

private void tryGrow(Object[] array, int oldCap) {
        // 释放了原来的独占锁 lock,这样的话,扩容操作和读操作可以同时进行,提高吞吐量
        lock.unlock(); 
        Object[] newArray = null;
        
        // 获取到allocationSpinLock才能进行数组扩容
        if (allocationSpinLock == 0 &&
            UNSAFE.compareAndSwapInt(this, allocationSpinLockOffset,
                                     0, 1)) {
            try {
                // 如果节点个数小于 64,那么增加的 oldCap + 2 的容量
                // 如果节点数大于等于 64,那么增加 oldCap 的一半
                // 所以节点数较小时,增长得快一些
                int newCap = oldCap + ((oldCap < 64) ?
                                       (oldCap + 2) : 
                                       (oldCap >> 1));
                // 可能溢出                       
                if (newCap - MAX_ARRAY_SIZE > 0) {   
                    int minCap = oldCap + 1;
                    if (minCap < 0 || minCap > MAX_ARRAY_SIZE)
                        throw new OutOfMemoryError();
                    newCap = MAX_ARRAY_SIZE;
                }
                // 如果 queue != array,那么说明有其他线程给 queue 分配了其他的空间
                if (newCap > oldCap && queue == array)
                    newArray = new Object[newCap];
            } finally {
                allocationSpinLock = 0;
            }
        }
        // 其他线程做了扩容操作
        if (newArray == null) 
            Thread.yield();
        lock.lock();
        // 将原来数组中的元素复制到新分配的大数组中
        if (newArray != null && queue == array) {
            queue = newArray;
            System.arraycopy(array, 0, newArray, 0, oldCap);
        }
    }
复制代码

put

public void put(E e) {
    // 直接调用 offer 方法,在这里,put 方法不会阻塞
    offer(e); 
}
public boolean offer(E e) {
    if (e == null)
        throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    // 首先获取到独占锁
    lock.lock();
    int n, cap;
    Object[] array;
    // 如果当前队列中的元素个数 >= 数组的大小,那么需要扩容了
    while ((n = size) >= (cap = (array = queue).length))
        tryGrow(array, cap);
    try {
        Comparator<? super E> cmp = comparator;
        // 节点添加到二叉堆中
        if (cmp == null)
            siftUpComparable(n, e, array);
        else
            siftUpUsingComparator(n, e, array, cmp);
        // 更新 size
        size = n + 1;
        // 唤醒等待的读线程
        notEmpty.signal();
    } finally {
        lock.unlock();
    }
    return true;
}
复制代码

可以看到,过程也很简单,获取锁,插入元素,调整二叉堆,关于堆,限于篇幅,我们后边会写文章详细介绍,这里不再赘述。

take

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    // 独占锁
    lock.lockInterruptibly();
    E result;
    try {
        // dequeue 出队
        while ( (result = dequeue()) == null)
            notEmpty.await();
    } finally {
        lock.unlock();
    }
    return result;
}
复制代码

同样是先获得独占锁,如果是空队列的话,需要等待,如果非空,直接拿出,注意同样需要调整二叉堆。

DelayQueue

顾名思义,是个延迟队列,什么意思呢?即,队列中每个元素都有过期时间,从队列获取元素时,只能获取过期元素

可以运用于以下场景:

  • 缓存系统的设计 使用此队列缓存元素有效期,开一个线程查询队列,一旦获取到,表示缓存有效期到了
  • 定时任务调度 使用此队列保存当天会执行的任务和时间,一旦获取到任务就执行,比如TimeQueue

该队列中的元素必须实现Delayed接口,同时必须实现compareTo方法指定元素顺序,比如让延时时间最长的元素在队列末尾

public interface Delayed extends Comparable<Delayed> {
    long getDelay(TimeUnit unit);
}
复制代码

该方法返回当前元素还需多长时间可用,去延迟队列中获取元素时,若元素没有到达延时时间就阻塞。

总结

又是一片很长很长的文。。。

  • ArrayBlockingQueue 底层是数组,有界队列,如果我们要使用生产者-消费者模式,这是非常好的选择。
  • LinkedBlockingQueue 底层是链表,可以当做无界和有界队列来使用,所以大家不要以为它就是无界队列。
  • SynchronousQueue 本身不带有空间来存储任何元素,使用上可以选择公平模式和非公平模式。
  • PriorityBlockingQueue 是无界队列,基于数组,数据结构为二叉堆,数组第一个也是树的根节点总是最小值。
  • DelayQueue也是个无界阻塞队列,使用PriorityQueue作为底层实现,只有延迟期满才可以获取元素

公众号 程序员二狗

每日原创文章,一起交流学习

猜你喜欢

转载自juejin.im/post/5db6bc97f265da4d525fce20
今日推荐