BlockingQueue源码分析

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 c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // Lock only for visibility, not mutual exclusion
        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();
        }
  }

列出主要的成员变量

    /** The queued items */
    final Object[] items;
    /** items index for next take, poll, peek or remove */
    int takeIndex;
    /** items index for next put, offer, or add */
    int putIndex;
    /** Number of elements in the queue */
    int count;
    /** Main lock guarding all access */
    final ReentrantLock lock;
    /** Condition for waiting takes */
    private final Condition notEmpty;
    /** Condition for waiting puts */
    private final Condition notFull;
  1. 插入 add、offer、put
//java.util.concurrent.ArrayBlockingQueue.add(E)
 public boolean add(E e) {
        return super.add(e);
    }
//java.util.AbstractQueue.add(E)
   public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

//java.util.concurrent.ArrayBlockingQueue.offer(E)
    public boolean offer(E e) {
//若e为null抛出空指针异常
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
//队列满了,直接返回false
            if (count == items.length)
                return false;
            else {
//元素入队
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

//java.util.concurrent.ArrayBlockingQueue.put(E)
    public void put(E e) throws InterruptedException {
//若e为null抛出空指针异常
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
//可响应中断的加锁操作
        lock.lockInterruptibly();
        try {
            while (count == items.length)
//阻塞,直到队列中有空间可用
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }
//java.util.concurrent.ArrayBlockingQueue.enqueue(E)
//添加元素到队列中
    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
//重置putIndex
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
//唤醒在notEmpty条件队列上等待的某个线程
        notEmpty.signal();
    }

添加元素API的一些特点:add内部调用了offer,返回成功或抛出异常。offer返回成功或失败。put阻塞直到元素放入队列,可响应中断。(add的元素不能是null,否则会产生空指针异常)

  1. 删除(出队)remove、poll、take
//java.util.AbstractQueue.remove()
    public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

//java.util.concurrent.ArrayBlockingQueue.poll()
    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
//出队一个元素,若队列为空返回一个null
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

//java.util.concurrent.ArrayBlockingQueue.take()
    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
//可响应中断的加锁操作
        lock.lockInterruptibly();
        try {
//阻塞直到队列中有元素能够出队
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
//java.util.concurrent.ArrayBlockingQueue.dequeue()
//元素出队
    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
//重置takeIndex
        if (++takeIndex == items.length)
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
//唤醒在notFull上等待的线程中的一个
        notFull.signal();
        return x;
    }

删除元素API的一些特点:remove内部调用了poll,返回出队元素或抛出异常。poll返回出队元素或null。take阻塞直到元素出队,可响应中断。

LinkedBlockingQueue

初始化

    public LinkedBlockingQueue() {
//默认初始化一个20多亿长度的队列
        this(Integer.MAX_VALUE);
    }

    public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
//初始化head和last
        last = head = new Node(null);
    }

    public LinkedBlockingQueue(Collection c) {
        this(Integer.MAX_VALUE);
        final ReentrantLock putLock = this.putLock;
        putLock.lock(); // Never contended, but necessary for visibility
        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));
                ++n;
            }
            count.set(n);
        } finally {
            putLock.unlock();
        }
    }

列出主要的成员变量

    /** The capacity bound, or Integer.MAX_VALUE if none */
    private final int capacity;
    /** Current number of elements */
    private final AtomicInteger count = new AtomicInteger();
    /**
     * Head of linked list.
     * Invariant: head.item == null
     */
    transient Node head;
    /**
     * Tail of linked list.
     * Invariant: last.next == null
     */
    private transient Node last;
    /** Lock held by take, poll, etc */
    private final ReentrantLock takeLock = new ReentrantLock();

    /** Wait queue for waiting takes */
    private final Condition notEmpty = takeLock.newCondition();

    /** Lock held by put, offer, etc */
    private final ReentrantLock putLock = new ReentrantLock();

    /** Wait queue for waiting puts */
    private final Condition notFull = putLock.newCondition();
  1. 插入 add、offer、put
//java.util.AbstractQueue.add(E)
   public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

//java.util.concurrent.LinkedBlockingQueue.offer(E)
    public boolean offer(E e) {
//入队的元素e为null,会抛出空指针异常
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
//使用原子类计数,判断队列是否已满。(应该比加锁快)
        if (count.get() == capacity)
            return false;
        int c = -1;
        Node node = new Node(e);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
//队列中还有空间
            if (count.get() < capacity) {
//入队
                enqueue(node);
//count加1
                c = count.getAndIncrement();
//元素入队后,队列还有空间。唤醒在notFull上等待的线程中的一个
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
//若c==0,表明元素入队前队列是空的。(此时删除元素那边的线程肯定在notEmpty上等待,这里需要执行唤醒)
        if (c == 0)
            signalNotEmpty();
//c大于等于0时表明元素入队成功
        return c >= 0;
    }

//java.util.concurrent.LinkedBlockingQueue.put(E)
    public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        // Note: convention in all put/take/etc is to preset local var
        // holding count negative to indicate failure unless set.
        int c = -1;
        Node node = new Node(e);
        final ReentrantLock putLock = this.putLock;
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly();
        try {
//这里上的时写锁,删除(出队)元素的操作可能也再同时执行。这里count可能会不断变化
            while (count.get() == capacity) {
                notFull.await();
            }
            enqueue(node);
            c = count.getAndIncrement();
//队列中还有空间,唤醒在notFull上等待的线程中的一个
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
//
        if (c == 0)
            signalNotEmpty();
    }
//java.util.concurrent.LinkedBlockingQueue.enqueue(Node)
//这里enqueue和下面的dequeue可能同时被调用,会有问题嘛?
    private void enqueue(Node node) {
        // assert putLock.isHeldByCurrentThread();
        // assert last.next == null;
        last = last.next = node;
    }

//java.util.concurrent.LinkedBlockingQueue.signalNotEmpty()
    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
    }

添加元素API的一些特点:同ArrayBlockingQueue

  1. 删除(出队)remove、poll、take
//java.util.AbstractQueue.remove()
    public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

//java.util.concurrent.LinkedBlockingQueue.poll()
    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();
//若c为2表明元素出队前,队列中有2个元素。若c为1,元素出队后队列就空了。所以这里需要判断c > 1
                if (c > 1)
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
//这里c==capacity,说明在出队之前队列是满的。添加元素的线程一定在等待,这里进行唤醒。
        if (c == capacity)
            signalNotFull();
        return x;
    }

//java.util.concurrent.LinkedBlockingQueue.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;
    }
//java.util.concurrent.LinkedBlockingQueue.dequeue()
////这里dequeue和上面的enqueue可能同时被调用,会有问题嘛?
    private E dequeue() {
        // assert takeLock.isHeldByCurrentThread();
        // assert head.item == null;
        Node h = head;
        Node first = h.next;
//h的next指向自己
        h.next = h; // help GC
        head = first;
        E x = first.item;
        first.item = null;
        return x;
    }

//java.util.concurrent.LinkedBlockingQueue.signalNotFull()
    private void signalNotFull() {
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            notFull.signal();
        } finally {
            putLock.unlock();
        }
    }

删除元素API的一些特点:同ArrayBlockingQueue

LinkedBlockingQueue相比于ArrayBlockingQueue,它在元素入队和出队这两种操作上使用了不同的锁。这意味着LinkedBlockingQueue可以同时执行入队和出队操作,而ArrayBlockingQueue中元素入队和出队时使用的是同一把锁,所以ArrayBlockingQueue入队和出队操作是不可能同时执行的。

总结

常用的队列 特点
ArrayListBlockingQueue 数组实现的有界阻塞队列,支持公平和非公平配置(ReentrantLock)
LinkedBlockingQueue 链表实现的有界阻塞队列,两把独立锁提高并发
PriorityBlockingQueue 数组实现的无界队列,数据结构为二叉堆(compareTo排序)
DelayQueue 队列使用PriorityQueue实现,队列中的元素需要是java.util.concurrent.Delayed
SynchronousQueue 不存储元素的阻塞队列,每个put操作必须等待一个take操作,反之亦然
LinkedTransferQueue 相比其他阻塞队列,多了tryTransfer和transfer方法(生产者将元素传递给消费者)
LinkedBlockingDeque 链表实现的双向阻塞队列,可以从队列两端插入和移除元素

你可能感兴趣的:(BlockingQueue源码分析)