BlockingQueue阻塞队列的实现方式及源码解析

BlockingQueue阻塞队列, 分为有界和无界队列, 常用的有界队列即为ArrayBlockingQueue, LinkedBlockingQueue, 虽然也有最大长度, 但最大长度为Integer.MAX_VALUE(21亿+), 也可以视为无界队列

BlockingQueue接口中有以下方法

public interface BlockingQueue<E> extends Queue<E> {
	// 添加元素, 如果已满, 抛出异常
    boolean add(E e);
    // 移除元素, 如果没有元素, 抛出元素
    boolean remove(Object o);
    
    // 添加元素, 如果已满返回false
    boolean offer(E e);
    // 添加元素, 如果已满等待指定时间, 超时返回false
    boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException;
    // 移除元素, 如果没有元素, 等待指定时间, 超时返回null
    E poll(long timeout, TimeUnit unit)
        throws InterruptedException;
    
    // 添加元素, 如果已满, 一直阻塞直到成功
    void put(E e) throws InterruptedException;
    // 移除元素, 如果没有元素, 一直阻塞到有元素
    E take() throws InterruptedException;
}    

Queue接口中有以下方法

public interface Queue<E> extends Collection<E> {
	// 添加元素, 如果已满, 抛出异常
	boolean add(E e);
    // 移除元素, 如果没有元素, 抛出元素
	E remove();
	
    // 添加元素, 如果已满返回false
	boolean offer(E e);
	// 移除元素, 如果没有, 返回空
	E poll();
	
	// 获取队列中首元素, 如果为空抛出异常(元素不出队列)
	E element();
	// 获取队列中首元素, 如果没有返回空(元素不出队列)
	E peek();
}

BlockingQueue有以下几种实现
ArrayBlockingQueue: 基于数组的有界阻塞队列
LinkedBlockingQueue: 基于单向链表的有界阻塞队列
PriorityBlockingQueue: 元素具有优先级的无界阻塞队列
DelayBlockingQueue: 使用PriorityBlockingQueue封装的具有延迟特性的无界阻塞队列
SynchronousQueue: 只存放单个元素的队列, 同步阻塞队列
LinkedTransferQueue: 链表组成的无界阻塞队列, 用于生产者在添加元素时, 需要将消息传递给消费者
LinkedBlockingDeque: 基于双向链表的无界阻塞队列

ArrayBlockingQueue, 可以创建公平队列和非公平队列, 公平队列: 在添加元素时, 如果有队列不为空, 则入队尾等待; 非公平队列, 添加元素时, 通过CAS交换当前state, 如果state为0并且CAS成功, 执行当前线程.

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
     // 通过数组实现有界队列
    final Object[] items;
    
    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();
    }

    public boolean add(E e) {
        return super.add(e);
    }

	// 父类中的add方法, 调用offer如果返回false, 抛出异常
    public boolean add(E e) {
        if (offer(e)) // 调用offer方法
            return true;
        else
            throw new IllegalStateException("Queue full");
    }
    
    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) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x; // 元素放入到数组中
        if (++putIndex == items.length) // 循环index, 避免出队时数组移动
            putIndex = 0;
        count++;
        notEmpty.signal(); // 通知消费
    }

	public boolean remove(Object o) {
        if (o == null) return false;
        final Object[] items = this.items;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count > 0) {
                final int putIndex = this.putIndex;
                int i = takeIndex; // 从指定index开始获取
                do {
                    if (o.equals(items[i])) { // 如果元素相同, remove
                        removeAt(i); // 删除元素, 并位移队列元素
                        return true;
                    }
                    if (++i == items.length)
                        i = 0;
                } while (i != putIndex);
            }
            return false;
        } finally {
            lock.unlock();
        }
    }

    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }
    
    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex]; // 指定当前获取元素index
        items[takeIndex] = null; // 置为null
        if (++takeIndex == items.length) // index向下移懂
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal(); // 唤醒生产线程
        return x;
    }
}

LinkedBlockingQueue, 使用单向链表实现, 内部使用了生产锁, 消费锁及CAS(count). 两个锁提升并发吞吐量.

public class LinkedBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
        
    // 定义单向链表元素结构
    static class Node<E> {
        E item;
        Node<E> next;
        Node(E x) { item = x; }
    }

	// 链表长度
	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();

	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 boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }
	
	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(); // count+1
                if (c + 1 < capacity) // 队列不满
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        if (c == 0) // 说明在添加元素之前, count为0, 已经阻塞了消费线程
            signalNotEmpty(); // 唤醒消费线程
        return c >= 0;
    }

	private void enqueue(Node<E> node) {
        // assert putLock.isHeldByCurrentThread();
        // assert last.next == null;
        last = last.next = node; // 队尾添加元素
    }

	public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

	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(); // count-1
                if (c > 1)
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == capacity) // 说明在消费元素之前, count为最大容量, 已经阻塞了生产线程
            signalNotFull(); // 唤起生产线程
        return x;
    }

	// 将head元素从链表移除, 并将下一个元素设置成head
	private E dequeue() {
        // assert takeLock.isHeldByCurrentThread();
        // assert head.item == null;
        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;
    }  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值