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<? extends E> 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<E>(null);
    }

    public LinkedBlockingQueue(Collection<? extends E> 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>(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<E> head;
    /**
     * Tail of linked list.
     * Invariant: last.next == null
     */
    private transient Node<E> 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<E> node = new Node<E>(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<E> node = new Node<E>(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<E>)
//这里enqueue和下面的dequeue可能同时被调用,会有问题嘛?
    private void enqueue(Node<E> 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<E> h = head;
        Node<E> 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 链表实现的双向阻塞队列,可以从队列两端插入和移除元素
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355