Java中的阻塞队列

本文深入探讨了ArrayBlockingQueue和LinkedBlockingQueue两种队列的内部实现机制,包括它们的数据结构、核心成员变量及关键方法。ArrayBlockingQueue基于数组实现,具有固定的容量,而LinkedBlockingQueue则基于链表,提供了更好的性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们先来看ArrayBlockingQueue类

先看作者给出的注释

* A bounded {@linkplain BlockingQueue blocking queue} backed by an
* array.  This queue orders elements FIFO (first-in-first-out).  The
* <em>head</em> of the queue is that element that has been on the
* queue the longest time.  The <em>tail</em> of the queue is that
* element that has been on the queue the shortest time. New elements
* are inserted at the tail of the queue, and the queue retrieval
* operations obtain elements at the head of the queue.
*

这是一个遵照FIFO先进先出基于数组实现的队列,处于头部的元素在队列中的 时间最久,相似的,在队尾的元素处于队列中的时间最短。新元素将会加入在队列的尾部,而队列的检索所操作的数据将是队列头部的数据。

* <p>This is a classic "bounded buffer", in which a
* fixed-sized array holds elements inserted by producers and
* extracted by consumers.  Once created, the capacity cannot be
* changed.  Attempts to {
@code put} an element into a full queue
* will result in the operation blocking; attempts to {
@code take} an
* element from an empty queue will similarly block.
*

这是一种经典的数据缓冲基于一个可变长的数组来存储数据,由生产者加入数据,消费者取得数据。一旦建立,容量不能再变化。当队列已满的时候加入元素则会阻塞操作,相应的,当队列为空的时候试图取数据会导致操作阻塞。

 

下面是这个类的一些成员

 

 

final Object[] items;

int takeIndex;

int putIndex;

int count;

final ReentrantLock lock;
 
private final Condition notEmpty;

private final Condition notFull;

 

 

 

items作为队列中的容器,由于是数组类,所以在使用过程中容量不能再发生变化。

takeIndex 队列中下一次take poll peek remove操作的下标

putIndex队列中下一次put offer add操作的下标

下面是队列中为了数组下标适应队列的方法

inal int inc(int i) {
    return (++i == items.length) ? 0 : i;
}

final int dec(int i) {
    return ((i == 0) ? items.length : i) - 1;
}

count队列中元素的个数。

notEmpty队列中协调取数据的通信条件。

notFull队列中协调加入数据的通信条件。

我们可以相应的看一下这个ArrayBlockingQueue类的构造方法。

 

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

public ArrayBlockingQueue(int capacity, boolean fair,
                          Collection<? extends E> c) {
    this(capacity, fair);

    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        int i = 0;
        try {
            for (E e : c) {
                checkNotNull(e);
                items[i++] = e;
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
            throw new IllegalArgumentException();
        }
        count = i;
        putIndex = (i == capacity) ? 0 : i;
    } finally {
        lock.unlock();
    }
}

 

 

 

显然队列的容量在构造方法中就已经作为参数确定,并在接下来的使用中不能再修改。

fair为true的时候,整个队列的所有操作尊从FIFO,如果为false,则整个队列的操作规则并没有被定义。

另外的在后面的构造方法中支持了在类初始化中就可以传入数据存储在队列中

 

下面是队列的几个基本操作

private void insert(E x) {
    items[putIndex] = x;
    putIndex = inc(putIndex);
    ++count;
    notEmpty.signal();
}

private E extract() {
    final Object[] items = this.items;
    E x = this.<E>cast(items[takeIndex]);
    items[takeIndex] = null;
    takeIndex = inc(takeIndex);
    --count;
    notFull.signal();
    return x;
}

void removeAt(int i) {
    final Object[] items = this.items; 
    if (i == takeIndex) {
        items[takeIndex] = null;
        takeIndex = inc(takeIndex);
    } else {
        for (;;) {
            int nexti = inc(i);
            if (nexti != putIndex) {
                items[i] = items[nexti];
                i = nexti;
            } else {
                items[i] = null;
                putIndex = i;
                break;
            }
        }
    }
    --count;
    notFull.signal();
}

 

insert()方法很简单在指向队列尾部的下标上存入数据putIndex指向下一个位置,更新队列中的元素个数count,最后试着唤醒由于队列空而阻塞的试图取数据线程。

 

extract()方法思路也很清晰取得takeIndex位置上的数据,将takeIndex指向下一个位置,唤醒由于队列满而阻塞的试图向队列中加入数据的线程。

removeAt()方法则是移除具体index上的数据。如果要移除数据的下标i正好是takeIndex那么只要将i位置置成null,takeIndex向下即可但如果并不是则需要将i + 1到putIndex前的数据向前一次复制,当前putIndex位置的数据置null,putIndex向前

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

 

上面真正给外部调用的offer方法,在调用insert()之前加锁,并在队列已满的时候直接返回失败。

 

而如果我们试图在给队列添加元素的时候遇到队列已满的时候等待队列空出位置呢直到时间超过我们的预期值

我么可以给出timeout以及timeout单位的参数


public boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException {

    checkNotNull(e);
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == items.length) {
            if (nanos <= 0)
                return false;
            nanos = notFull.awaitNanos(nanos);
        }
        insert(e);
        return true;
    } finally {
        lock.unlock();
    }
}

在前面offer()方法 的前提下给出了timeout参数。

 

public E poll() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        return (count == 0) ? null : extract();
    } finally {
        lock.unlock();
    }
}
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
    long nanos = unit.toNanos(timeout);
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == 0) {
            if (nanos <= 0)
                return null;
            nanos = notEmpty.awaitNanos(nanos);
        }
        return extract();
    } finally {
        lock.unlock();
    }
}

 

取数据的操作与存数据的操作大同小异。

 

 

下面是LinkedBlockingQueue类的分析。

与本文的前者相比,虽然LinkedBlockingQueue也是遵从了FIFO的队列,但是,该类是通过Node类来存储数据的,下面是Node类的具体结构。

static class Node<E> {
    E item;

    Node<E> next;

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

 

非常经典的链表结点结构。这导致了LinkedBlockingQueue在存取数据上相对于前者的性能优势,但是在可预见性上略逊一筹。

 

下面是LinkedBlockingQueue类的成员

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

 

大部分成员都与前者类似,但是基于链表的基础的实现。

 

但值得一提的是在这里LinkedBlockingQueue采用存取两个锁的实现,相对前者,在具体使用中更加灵活。

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();
            if (n == capacity)
                throw new IllegalStateException("Queue full");
            enqueue(new Node<E>(e));
            ++n;
        }
        count.set(n);
    } finally {
        putLock.unlock();
    }
}

在构造方法上与前者差别不大,LinkedBlockingQueue容量默认为Integer.MAX_VALE。但是值得一提的是在往队列加入数据的时候只需要给putLock()加锁,使得别的线程在取数据的时候更加灵活。

private void enqueue(Node<E> node) {
    last = last.next = node;
}

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

 

在具体的存取数据上只是基于链表的操作。

 

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);
    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()方法。

 

与前者不同的是,存储Node的类在这里动态生成实例进行存储。同时由于两个锁的存在对于内部数据个数的要求更加苛刻所以采用了AtomicInteger类来保证在并发条件下数据的准确性。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值