谈谈阻塞队列LinkedBlockingQueue

938 阅读4分钟

这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战

上一篇讲了ArrayBlockingQueue的相关源码,本篇继续看LinkedBlockingQueue。LinkedBlockingQueue是基于单向链表的阻塞队列,先进先出的顺序,支持多线程并发操作。LinkedBlockingQueue可认为是无界队列,多用于任务队列。

主要属性

//节点很简单,实现了一个单向链表
static class Node<E> {
    E item;
    Node<E> next;

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

//阻塞队列的大小,默认为Integer.MAX_VALUE 
private final int capacity;

//当前阻塞队列中的元素个数 
private final AtomicInteger count = new AtomicInteger();

//阻塞队列的头结点
transient Node<E> head;

// 阻塞队列的尾节点
private transient Node<E> last;

// 获取并移除元素时使用的锁,如take, poll, etc
private final ReentrantLock takeLock = new ReentrantLock();

//notEmpty条件对象,当队列没有数据时用于挂起执行删除的线程 
private final Condition notEmpty = takeLock.newCondition();

// 添加元素时使用的锁如 put, offer, etc 
private final ReentrantLock putLock = new ReentrantLock();

// notFull条件对象,当队列数据已满时用于挂起执行添加的线程 
private final Condition notFull = putLock.newCondition();

每个添加到LinkedBlockingQueue队列中的数据都将被封装成Node节点,添加到链表队列中,其中head和last分别指向队列的头结点和尾结点。与ArrayBlockingQueue不同的是,LinkedBlockingQueue内部分别使用了takeLock 和 putLock 对并发进行控制,添加和删除操作并不是互斥操作,可以同时进行,这样也就可以大大提高吞吐量。

主要方法

signalNotEmpty()和signalNotFull()

notEmpty/notFull分别对应非空和非满锁的条件监视器,signalNotEmpty()和signalNotFull()方法分别负责唤醒对应的入队、出队线程:

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 {
        putLoct.unlock();
    }
}

构造函数

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

初始化队列容量、头尾节点。

元素的插入

队列的插入方式分为三种,非阻塞插入、超时阻塞插入、阻塞插入 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();
      // 判断队列+1是否已满
      if (c + 1 < capacity)
        notFull.signal();
     }
  } finally {
    putLock.unlock();
  }
  // 代表本次插入元素成功,发送队列不为空信号
  if (c == 0)
    signalNotEmpty();
  return c >= 0;
}

private void enqueue(Node<E> node) {
  // 将node赋值给当前的last.next,再将last设置为node
  last = last.next = node;
}

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.signal()
    while (count.get() == capacity) {
      notFull.await();
    }
    // 插入元素
    enqueue(node);
    c = count.getAndIncrement();
    if (c + 1 < capacity)
      notFull.signal();
    } finally {
      putLock.unlock();
    }
    if (c == 0)
      signalNotEmpty();
}

offer(E e, long timeout, TimeUnit unit),只是在线程阻塞的时候,加入了一个等待时间

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 {
        // 等待超时时间nanos,超时时间到了返回false
        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;
}

仅仅对put方法改动了一点,当队列没有可用元素的时候,不同于put方法的阻塞等待,offer方法直接方法false。

元素的获取

队列获取元素,同样有三种方式,非阻塞获取、超时阻塞获取、阻塞获取 poll(),当队列为空时,直接返回null

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

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

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();
    }
    // 如果成功获取元素,则发送队列不满信号
    if (c == capacity)
      signalNotFull();
    return x;
}

poll(E e, long timeout, TimeUnit unit),如果有元素直接出队,如果队列为空。判断是否超时,超时返回null,未超时则接着等待,直到队列不为空或等待超时或被中断。

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();
            //如果节点数1,说明可以唤醒一个被阻塞的出队线程
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        //如果出队前,队列是满的,则唤醒一个被take()阻塞的线程
        if (c == capacity)
            signalNotFull();
        return x;
    }

删除方法

public boolean remove(Object o) {
    if (o == null) return false;
    // 两个lock全部上锁
    fullyLock();
    try {
        // 从head开始遍历元素,直到最后一个元素
        for (Node<E> trail = head, p = trail.next;
             p != null;
             trail = p, p = p.next) {
            // 如果找到相等的元素,调用unlink方法删除元素
            if (o.equals(p.item)) {
                unlink(p, trail);
                return true;
            }
        }
        return false;
    } finally {
        // 两个lock全部解锁
        fullyUnlock();
    }
}

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

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

因为remove方法使用两个锁全部上锁,所以其他操作都需要等待它完成。

总结

LinkedBlockingQueue是一个一个基于已链接节点的、范围任意(相对而论)的blocking queue。其中offer与poll是非阻塞的,put与take是阻塞的。入队使用入队锁,出队使用出队锁。单形参的offer与poll中调用的是lock()方法,阻塞获取锁资源。