java併發編程基礎——阻塞隊列BlockingQueue源碼分析

一、摘要

  BlockingQueue通常用於一個線程在生產對象,而另外一個線程在消費這些對象的場景,例如在線程池中,當運行的線程數目大於核心的線程數目時候,經常就會把新來的線程對象放到BlockingQueue中去。

二、阻塞隊列原理

  原理簡單的來講:就是一個線程往隊列裏面放,而另外的一個線程從裏面取

  當線程持續的產生新對象並放入到隊列中,直到隊列達到它所能容納的臨界點。注意,隊列的容量是有限的,不可能一直往裏面插入對象。如果隊列到達了臨界點時,這個時候再想往隊列中插入元素則會產生阻塞,直到另一端從隊列中進行消費了,這個時候阻塞現象纔不會發生。另外當去消費一個空的隊列時候,這個線程也會產生阻塞現象,直到一個線程把對象插入到隊列中

三、BlockingQueue常用方法總結

  拋出異常 特殊值 阻塞 超時
插入 add(e) offer(e) put(e) offer(e,time,unit)
移除 remove(e) poll take() poll(time,unit)
檢查 element(e) peek 不可用 不可用

  四組不同的行爲方式解釋:
    1.  拋異常:如果試圖的操作無法立即執行,拋一個異常。
    2.  特定值:如果試圖的操作無法立即執行,返回一個特定的值(常常是 true / false)。
    3.  阻塞:如果試圖的操作無法立即執行,該方法調用將會發生阻塞,直到能夠執行。
    4.  超時:如果試圖的操作無法立即執行,該方法調用將會發生阻塞,直到能夠執行,但等
      待時間不會超過給定值。返回一個特定值以告知該操作是否成功(典型的是 true / false)。
      無法向一個 BlockingQueue 中插入 null。如果你試圖插入 null,BlockingQueue 將會拋出
      一個 NullPointerException。

 

四、BlockingQueue源碼分析

  1、通過IDE可以明顯的看到BlockingQueue是一個接口,我們在寫代碼的時候需要實現這個接口

    java.util.concurrent 具有以下 BlockingQueue 接口的實現(Java 8):

      

五、數組阻塞隊列ArrayBlockingQueue分析

  1、原理分析

    首先ArrayBlockingQueue 類實現了 BlockingQueue 接口。其次ArrayBlockingQueue 是一個有界的阻塞隊列,其內部實現是將對象放到一個數組裏,所以一旦創建了該隊列,就不能再增加其容量了。最後ArrayBlockingQueue 內部以 FIFO(先進先出)的順序對元素進行存儲。

  2、ArrayBlockingQueue的方法(下面着重分析put()和take()二者方法)

    此構造方法中,我們能看到傳入了兩個參數,capacity代表着隊列的容量大小,而boolean類型的參數則是判斷是否爲公平鎖,如果爲true,則先到的線程會先得到鎖對象,    反之則有操作系統去決定哪個線程獲得鎖,大多數情況下都是設置爲false,這樣性能會高點

    在put方法中,我們能看到在執行put方法時,我們必須要對其進行加鎖操作,從而保證線程的安全性。其次會去判斷其隊列是否飽滿了,飽滿時則會發生阻塞現象,直到被其他線程喚醒時插入元素,接着會去調用notEmpty.signal()方法,間接的利用take方法將隊列中的元素取走,最後將鎖釋放。

       同理可以看出take()方法是相反的,不再做詳細介紹,代碼註釋已給出

    add(),put()和offer()精簡源代碼如下:

/** The queued items */
    final Object[] items;      //利用數組來存儲元素
  
    final ReentrantLock lock;

    /** Condition for waiting takes */
    private final Condition notEmpty;  //定義一個Condition對象,用來對take進行操作

    /** Condition for waiting puts */
    private final Condition notFull;  //定義一個Condition對象,用來對put進行操作

    /**
     * Creates an {@code ArrayBlockingQueue} with the given (fixed)
     * capacity and the specified access policy.
     *
     * @param capacity the capacity of this queue
     * @param fair if {@code true} then queue accesses for threads blocked
     *        on insertion or removal, are processed in FIFO order;
     *        if {@code false} the access order is unspecified.
     * @throws IllegalArgumentException if {@code capacity < 1}
     */
    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();
    }
====================================put()方法============================================
  /**
 * Inserts the specified element at the tail of this queue, waiting
 * for space to become available if the queue is full.
 *
 * @throws InterruptedException {@inheritDoc}
 * @throws NullPointerException {@inheritDoc}
 */
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();
    }
}


  /**
     * Inserts element at current put position, advances, and signals.
     * Call only when holding lock.
     */
    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)
            putIndex = 0;
        count++;
        notEmpty.signal();  //通知take那邊消費其元素
    }

==============================take()方法=============================================

 public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;  //加鎖
    lock.lockInterruptibly();
    try {
        while (count == 0)
            notEmpty.await();  //隊列爲空時,將使這個線程進入阻塞狀態,直到被其他線程喚醒時取出元素
        return dequeue();  //消費對頭中的元素
    } finally {
        lock.unlock();
    }
}

  /**
 * Extracts element at current take position, advances, and signals.
 * Call only when holding lock.
 */
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;
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    notFull.signal();  //通知put那邊消費其元素
    return x;
}

 

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


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

----------------------offer()------------------------------
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);
            }
            enqueue(e);
            return true;
        } finally {
            lock.unlock();
        }
    }

六、鏈式阻塞隊列LinkedBlockingQueue分析

  1、原理分析

    LinkedBlockingQueue 類實現了 BlockingQueue 接口。同時LinkedBlockingQueue 內部以一個鏈式結構(鏈接節點)對其元素進行存儲。如果需要的話,這一鏈式結構可以選擇一個上限。如果沒有定義上限,將使用 Integer.MAX_VALUE 作爲上限。LinkedBlockingQueue 內部以 FIFO(先進先出)的順序對元素進行存儲。

  2、LinkedBlockingQueue方法分析

    針對LinkedBlockingQueue的構造方法中,我們能看到沒有定義上限時,會使用Integer.MAX_VALUE 作爲上限

    其次針對put等方法時,原理與ArrayBlockingQueue大致相同,只不過是基於鏈表去實現的

    源碼精簡如下:

/** The capacity bound, or Integer.MAX_VALUE if none */
    //鏈表的容量
    private final int capacity;

    //當前元素個數
    private final AtomicInteger count = new AtomicInteger();

    //鏈表頭節點
    transient Node<E> head;

    //鏈表尾節點
    private transient Node<E> last;

    /** Lock held by take, poll, etc */
    //出隊列鎖
    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;
        //初始化頭尾節點的值,設置均爲null
        last = head = new Node<E>(null);
    }

    //往對尾中插入元素,隊列滿時,則會發生阻塞,直到有元素消費了或者線程中斷了
     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(); //則加入到出隊列等待中,直到隊列不滿了,這時就會被其他線程notFull.signal()喚醒
            }
            enqueue(node);//將元素入隊列
            c = count.getAndIncrement(); //對當前隊列元素個數加1
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }

    //出隊列,大致原理與入隊列相反,當隊列爲空時,則會阻塞,直到隊列不爲空或者線程中斷
    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;
    }

七、ArrayBlockingQueue和LinkedBlockingQueue源碼比較

  在上述源碼過程我們能發現:

  1、入隊列時,當隊列滿了,則會發生阻塞,直到隊列消費了數據或者線程被中斷了纔會喚醒

  2、出隊列時,當隊列爲空時,則會發生阻塞,直到隊列中有數據了或者線程被中斷了纔會喚醒

  源碼注意:

    ArrayBlockingQueue源碼中,共用的是同一把鎖

    LinkedBlockingQueue源碼中,則是用到了兩把鎖,一把是入隊列鎖,另一把是出隊列鎖

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章