16.jdk源码阅读之ArrayBlockingQueue

1. 写在前面

ArrayBlockingQueue 是 Java 中 java.util.concurrent 包的一部分,是一个基于数组的有界阻塞队列。它在多线程环境中非常有用,因为它提供了线程安全的方式来在生产者和消费者之间传递数据。
在正式阅读ArrayBlockingQueue的源码之前,有几个问题看看大家日常工作中有没有思考过:

  1. ArrayBlockingQueue 和 LinkedBlockingQueue 有什么区别?
  2. ArrayBlockingQueue 的公平性策略是什么?
  3. ArrayBlockingQueue 是如何实现线程安全的?
  4. ArrayBlockingQueue 的 put 和 take 方法如何工作?
  5. ArrayBlockingQueue 的内部数组是如何管理的?
  6. ArrayBlockingQueue 的 remainingCapacity 方法有什么用?
  7. 如何选择 ArrayBlockingQueue 的容量?

2. 从使用说起

下面是一个简单的示例,展示了如何使用 ArrayBlockingQueue 来实现生产者-消费者模式。

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ArrayBlockingQueueExample {
    public static void main(String[] args) {
        // 创建一个容量为 5 的 ArrayBlockingQueue
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);

        // 创建并启动生产者线程
        Thread producerThread = new Thread(new Producer(queue));
        producerThread.start();

        // 创建并启动消费者线程
        Thread consumerThread = new Thread(new Consumer(queue));
        consumerThread.start();
    }
}

// 生产者类
class Producer implements Runnable {
    private BlockingQueue<Integer> queue;

    public Producer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("Producing: " + i);
                queue.put(i);  // 如果队列已满,put 方法会阻塞
                Thread.sleep(500);  // 模拟生产时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

// 消费者类
class Consumer implements Runnable {
    private BlockingQueue<Integer> queue;

    public Consumer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Integer item = queue.take();  // 如果队列为空,take 方法会阻塞
                System.out.println("Consuming: " + item);
                Thread.sleep(1000);  // 模拟消费时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

2.1 代码解释

2.1.1 创建队列

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5);

创建一个容量为 5 的 ArrayBlockingQueue。

2.1.2 生产者类

class Producer implements Runnable {
    private BlockingQueue<Integer> queue;

    public Producer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("Producing: " + i);
                queue.put(i);  // 如果队列已满,put 方法会阻塞
                Thread.sleep(500);  // 模拟生产时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

生产者会生成 10 个整数并将它们放入队列中。如果队列已满,put 方法会阻塞直到有空间。

2.1.3 消费者类

class Consumer implements Runnable {
    private BlockingQueue<Integer> queue;

    public Consumer(BlockingQueue<Integer> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Integer item = queue.take();  // 如果队列为空,take 方法会阻塞
                System.out.println("Consuming: " + item);
                Thread.sleep(1000);  // 模拟消费时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

消费者会不断地从队列中取出整数并处理它们。如果队列为空,take 方法会阻塞直到有元素可用。

2.1.4 启动线程

Thread producerThread = new Thread(new Producer(queue));
producerThread.start();

Thread consumerThread = new Thread(new Consumer(queue));
consumerThread.start();

创建并启动生产者和消费者线程。

2.1.5 运行结果

运行上述代码后,你会看到生产者和消费者在控制台上输出的消息,类似于:

Producing: 0
Producing: 1
Consuming: 0
Producing: 2
Producing: 3
Consuming: 1
Producing: 4
Producing: 5
Consuming: 2

3. 全局视角

在这里插入图片描述
ArrayBlockingQueue 继承自 AbstractQueue,而 AbstractQueue 又继承自 AbstractCollection。ArrayBlockingQueue 实现了多个接口:

  • BlockingQueue
  • Serializable
    这些接口定义了 ArrayBlockingQueue 的行为和功能。

3.1 java.util.AbstractCollection

这是一个抽象类,部分实现了 Collection 接口。它提供了一些默认的方法实现,比如 addAll(), removeAll(), retainAll() 等。

3.2 java.util.AbstractQueue

这是一个抽象类,部分实现了 Queue 接口。它提供了一些默认的方法实现,比如 add(), remove(), element() 等。

3.3 java.util.concurrent.ArrayBlockingQueue

这是一个具体的类,继承了 AbstractQueue,并实现了 BlockingQueue 和 Serializable 接口。它提供了基于数组的有界阻塞队列的具体实现。

3.4 java.util.concurrent.BlockingQueue

这是一个接口,继承了 Queue 接口,并添加了阻塞操作的方法,如 put(), take(), offer(), poll() 等。ArrayBlockingQueue 实现了这些方法,使其能够在多线程环境中安全地使用。

3.5 java.io.Serializable

这是一个标记接口,表示实现该接口的类可以被序列化。ArrayBlockingQueue 实现了这个接口,因此它的实例可以被序列化和反序列化。

4. ArrayBlockingQueue 和 LinkedBlockingQueue 有什么区别?

  • 数据结构:ArrayBlockingQueue 基于数组实现,而 LinkedBlockingQueue 基于链表实现。
  • 容量:ArrayBlockingQueue 是有界的,容量在创建时指定;LinkedBlockingQueue 可以是无界的(默认容量为 Integer.MAX_VALUE)或有界的(在创建时指定)。
  • 性能:ArrayBlockingQueue 通常具有更低的内存开销和更高的吞吐量,因为它使用数组存储元素;LinkedBlockingQueue 由于链表的特性,在高并发情况下可能会有更好的性能。
  • 锁机制:ArrayBlockingQueue 使用单一的锁来控制队列的插入和移除操作;LinkedBlockingQueue 使用两个独立的锁来分别控制插入和移除操作。

4.1 ArrayBlockingQueue 的锁机制

ArrayBlockingQueue 使用单一的锁(ReentrantLock)来控制对队列的并发访问。它还使用两个条件对象(notEmpty 和 notFull)来管理队列的空和满状态,从而实现阻塞操作。

4.1.1 主要成员变量

private final ReentrantLock lock;
private final Condition notEmpty;
private final Condition notFull;
private final Object[] items;
private int takeIndex;
private int putIndex;
private int count;
  • lock:用于保护对共享资源的并发访问。
  • notEmpty:在队列为空时,阻塞等待的条件。
  • notFull:在队列满时,阻塞等待的条件。
  • items:存储队列元素的数组。
  • takeIndex:指向下一个要取出元素的位置。
  • putIndex:指向下一个要插入元素的位置。
  • count:当前队列中的元素数量。

4.1.2 插入操作 (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();
    }
}

  • 获取锁 lock.lockInterruptibly()。
  • 如果队列已满,调用 notFull.await() 阻塞等待。
  • 调用 enqueue(e) 插入元素。
  • 释放锁 lock.unlock()。

4.1.3 移除操作 (take 方法)

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

  • 获取锁 lock.lockInterruptibly()。
  • 如果队列为空,调用 notEmpty.await() 阻塞等待。
  • 调用 dequeue() 移除元素。
  • 释放锁 lock.unlock()。

4.2 LinkedBlockingQueue 的锁机制

LinkedBlockingQueue 使用两个独立的锁(takeLock 和 putLock)来分别控制插入和移除操作。这种设计可以提高并发性能,因为插入和移除操作可以在不互相干扰的情况下并行进行。

4.2.1 主要成员变量

private final int capacity;
private final AtomicInteger count = new AtomicInteger();
private final ReentrantLock takeLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition();
private final ReentrantLock putLock = new ReentrantLock();
private final Condition notFull = putLock.newCondition();
transient Node<E> head;
private transient Node<E> last;

  • capacity:队列的容量。
  • count:当前队列中的元素数量。
  • takeLock:用于保护移除操作的锁。
  • notEmpty:在队列为空时,阻塞等待的条件。
  • putLock:用于保护插入操作的锁。
  • notFull:在队列满时,阻塞等待的条件。
  • head:指向队列头部的节点。
  • last:指向队列尾部的节点。

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

  • 获取插入锁 putLock.lockInterruptibly()。
  • 如果队列已满,调用 notFull.await() 阻塞等待。
  • 调用 enqueue(node) 插入元素。
  • 更新元素数量 count.getAndIncrement()。
  • 释放插入锁 putLock.unlock()。
  • 如果队列之前为空,调用 signalNotEmpty() 唤醒等待的消费者。

4.2.3 移除操作 (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;
}

  • 获取移除锁 takeLock.lockInterruptibly()。
  • 如果队列为空,调用 notEmpty.await() 阻塞等待。
  • 调用 dequeue() 移除元素。
  • 更新元素数量 count.getAndDecrement()。
  • 释放移除锁 takeLock.unlock()。
  • 如果队列之前已满,调用 signalNotFull() 唤醒等待的生产者。

5. ArrayBlockingQueue 的公平性策略是什么?

公平性策略确保线程按照它们请求的顺序访问队列。默认情况下,ArrayBlockingQueue 不使用公平性策略(即非公平),这可能导致线程饥饿。通过在构造函数中传递 true 可以启用公平性策略:

ArrayBlockingQueue<Integer> fairQueue = new ArrayBlockingQueue<>(10, true);

6. ArrayBlockingQueue 是如何实现线程安全的?

ArrayBlockingQueue 使用内部锁(ReentrantLock)来控制对共享资源的并发访问。插入和移除操作都使用同一个锁,这确保了在任何给定时间只有一个线程可以执行插入或移除操作。此外,它使用两个条件对象(notEmpty 和 notFull)来管理队列的空和满状态,从而实现阻塞操作。

7. ArrayBlockingQueue 的 put 和 take 方法如何工作?

  • put(E e):如果队列已满,调用线程会被阻塞,直到有空间可用。一旦有空间可用,元素被插入队列,调用线程被唤醒。
  • take():如果队列为空,调用线程会被阻塞,直到有元素可用。一旦有元素可用,元素被移除队列,调用线程被唤醒。

8. ArrayBlockingQueue 的内部数组是如何管理的?

ArrayBlockingQueue 使用一个固定大小的数组来存储元素。它通过两个指针(takeIndex 和 putIndex)来跟踪队列的头部和尾部。插入操作将元素添加到 putIndex 位置,并递增 putIndex;移除操作从 takeIndex 位置取出元素,并递增 takeIndex。当指针超过数组的末尾时,它们会循环回到数组的开头。

9. ArrayBlockingQueue 的 remainingCapacity 方法有什么用?

remainingCapacity() 方法返回队列中剩余的可用空间,即可以插入的元素数量。这对于需要监控队列使用情况的应用程序非常有用。

ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
int remainingCapacity = queue.remainingCapacity(); // 返回 10

10. 如何选择 ArrayBlockingQueue 的容量?

选择 ArrayBlockingQueue 的容量应根据具体应用的需求和负载来决定。需要考虑以下因素:

  • 生产者和消费者的速率:确保队列容量足够大,以避免频繁的阻塞。
  • 内存限制:过大的容量可能会导致内存占用过高。
  • 应用的实时性要求:对于实时性要求高的应用,选择适当的容量以平衡队列的吞吐量和延迟。

系列文章

1.JDK源码阅读之环境搭建

2.JDK源码阅读之目录介绍

3.jdk源码阅读之ArrayList(上)

4.jdk源码阅读之ArrayList(下)

5.jdk源码阅读之HashMap

6.jdk源码阅读之HashMap(下)

7.jdk源码阅读之ConcurrentHashMap(上)

8.jdk源码阅读之ConcurrentHashMap(下)

9.jdk源码阅读之ThreadLocal

10.jdk源码阅读之ReentrantLock

11.jdk源码阅读之CountDownLatch

12.jdk源码阅读之CyclicBarrier

13.jdk源码阅读之Semaphore

14.jdk源码阅读之线程池(上)

15.jdk源码阅读之线程池(下)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

至真源

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值