BlockingQueue介面及實現類分析
1 BlockingQueue 介面及其實現類
BlocingQueue介面定義如下,僅列舉幾個常用方法:
- put(E) 在佇列尾部放入元素,若佇列滿則等待;
- take() 取佇列頭部元素返回,若佇列空則等待;
- offer(E) 在佇列尾部放入元素,若成功則返回true, 否則false;不阻塞;
- poll() 取佇列頭部元素返回,若有元素則返回元素,否則null;不阻塞;
實現BlockingQueue的常用介面:
- ArrayBlockingQueue: 使用迴圈陣列實現佇列,由一把鎖控制put 和 take, 同一把鎖上實現了兩個等待佇列(Condition);
- LinkedBlockingQueue: 使用連結串列實現佇列,由兩把鎖分別控制put 和 take,兩個等待佇列分別在兩把鎖上;
- PriorityBlockingQueue: 使用小頂堆實現優先順序佇列,取出元素順序有Comparable, Comparator決定,多執行緒安全;
2 ArrayBlockingQueue 原始碼解讀
ArrayBlockingQueue建立的時候需要指定容量capacity(可以儲存的最大的元素個數,因為它不會自動擴容)。其中一個構造方法為:
[java] view plain copy print?- public ArrayBlockingQueue(int capacity, boolean fair) {
- if (capacity <= 0)
- throw
- this.items = (E[]) new Object[capacity];
- lock = new ReentrantLock(fair);
- notEmpty = lock.newCondition();
- notFull = lock.newCondition();
- }
ArrayBlockingQueue類中定義的變數有:
[java] view plain copy print?- /** The queued items */
- privatefinal E[] items;
- /** items index for next take, poll or remove */
- privateint takeIndex;
- /** items index for next put, offer, or add. */
- privateint putIndex;
- /** Number of items in the queue */
- privateint count;
- /*
- * Concurrency control uses the classic two-condition algorithm
- * found in any textbook.
- */
- /** Main lock guarding all access */
- privatefinal ReentrantLock lock;
- /** Condition for waiting takes */
- privatefinal Condition notEmpty;
- /** Condition for waiting puts */
- privatefinal Condition notFull;
put(E e)方法的原始碼如下。進行put操作之前,必須獲得鎖並進行加鎖操作,以保證執行緒安全性。加鎖後,若發現佇列已滿,則呼叫notFull.await()方法,如當前執行緒陷入等待。直到其他執行緒take走某個元素後,會呼叫notFull.signal()方法來啟用該執行緒。啟用之後,繼續下面的插入操作。
[java] view plain copy print?- /**
- * Inserts the specified element at the tail of this queue, waiting
- * for space to become available if the queue is full.
- *
- */
- publicvoid put(E e) throws InterruptedException {
- //不能存放 null 元素
- if (e == null) thrownew NullPointerException();
- final E[] items = this.items; //陣列佇列
- final ReentrantLock lock = this.lock;
- //加鎖
- lock.lockInterruptibly();
- try {
- try {
- //當佇列滿時,呼叫notFull.await()方法,使該執行緒阻塞。
- //直到take掉某個元素後,呼叫notFull.signal()方法啟用該執行緒。
- while (count == items.length)
- notFull.await();
- } catch (InterruptedException ie) {
- notFull.signal(); // propagate to non-interrupted thread
- throw ie;
- }
- //把元素 e 插入到隊尾
- insert(e);
- } finally {
- //解鎖
- lock.unlock();
- }
- }
- /**
- * Inserts element at current put position, advances, and signals.
- * Call only when holding lock.
- */
- privatevoid insert(E x) {
- items[putIndex] = x;
- //下標加1或者等於0
- putIndex = inc(putIndex);
- ++count; //計數加1
- //若有take()執行緒陷入阻塞,則該操作啟用take()執行緒,繼續進行取元素操作。
- //若沒有take()執行緒陷入阻塞,則該操作無意義。
- notEmpty.signal();
- }
- **
- * Circularly increment i.
- */
- finalint inc(int i) {
- //此處可以看到使用了迴圈佇列
- return (++i == items.length)? 0 : i;
- }
- public E take() throws InterruptedException {
- final ReentrantLock lock = this.lock;
- lock.lockInterruptibly(); //加鎖
- try {
- try {
- //當佇列空時,呼叫notEmpty.await()方法,使該執行緒阻塞。
- //直到take掉某個元素後,呼叫notEmpty.signal()方法啟用該執行緒。
- while (count == 0)
- notEmpty.await();
- } catch (InterruptedException ie) {
- notEmpty.signal(); // propagate to non-interrupted thread
- throw ie;
- }
- //取出隊頭元素
- E x = extract();
- return x;
- } finally {
- lock.unlock(); //解鎖
- }
- }
- /**
- * Extracts element at current take position, advances, and signals.
- * Call only when holding lock.
- */
- private E extract() {
- final E[] items = this.items;
- E x = items[takeIndex];
- items[takeIndex] = null;
- takeIndex = inc(takeIndex);
- --count;
- notFull.signal();
- return x;
- }
3 LinkedBlockingQueue 原始碼解讀
基於連結串列的阻塞佇列,同ArrayListBlockingQueue類似,其內部也維持著一個數據緩衝佇列(該佇列由一個連結串列構成),當生產者往佇列中放入一個數據時,佇列會從生產者手中獲取資料,並快取在佇列內部,而生產者立即返回;只有當佇列緩衝區達到最大值快取容量時(LinkedBlockingQueue可以通過建構函式指定該值),才會阻塞生產者佇列,直到消費者從佇列中消費掉一份資料,生產者執行緒會被喚醒,反之對於消費者這端的處理也基於同樣的原理。而LinkedBlockingQueue之所以能夠高效的處理併發資料,還因為其對於生產者端和消費者端分別採用了獨立的鎖來控制資料同步,這也意味著在高併發的情況下生產者和消費者可以並行地操作佇列中的資料,以此來提高整個佇列的併發效能。
作為開發者,我們需要注意的是,如果構造一個LinkedBlockingQueue物件,而沒有指定其容量大小,LinkedBlockingQueue會預設一個類似無限大小的容量(Integer.MAX_VALUE),這樣的話,如果生產者的速度一旦大於消費者的速度,也許還沒有等到佇列滿阻塞產生,系統記憶體就有可能已被消耗殆盡了。
LinkedBlockingQueue 類中定義的變數有:
[java] view plain copy print?- /** The capacity bound, or Integer.MAX_VALUE if none */
- privatefinalint capacity;
- /** Current number of elements */
- privatefinal AtomicInteger count = new AtomicInteger(0);
- /** Head of linked list */
- privatetransient Node<E> head;
- /** Tail of linked list */
- privatetransient Node<E> last;
- /** Lock held by take, poll, etc */
- privatefinal ReentrantLock takeLock = new ReentrantLock();
- /** Wait queue for waiting takes */
- privatefinal Condition notEmpty = takeLock.newCondition();
- /** Lock held by put, offer, etc */
- privatefinal ReentrantLock putLock = new ReentrantLock();
- /** Wait queue for waiting puts */
- privatefinal Condition notFull = putLock.newCondition();
- /**
- * Inserts the specified element at the tail of this queue, waiting if
- * necessary for space to become available.
- */
- publicvoid put(E e) throws InterruptedException {
- if (e == null) thrownew NullPointerException();
- // Note: convention in all put/take/etc is to preset local var
- // holding count negative to indicate failure unless set.
- int c = -1;
- final ReentrantLock putLock = this.putLock;
- final AtomicInteger count = this.count;
- putLock.lockInterruptibly(); //加 putLock 鎖
- try {
- /*
- * Note that count is used in wait guard even though it is
- * not protected by lock. This works because count can
- * only decrease at this point (all other puts are shut
- * out by lock), and we (or some other waiting put) are
- * signalled if it ever changes from
- * capacity. Similarly for all other uses of count in
- * other wait guards.
- */
- //當佇列滿時,呼叫notFull.await()方法釋放鎖,陷入等待狀態。
- //有兩種情況會啟用該執行緒
- //第一、 某個put執行緒新增元素後,發現佇列有空餘,就呼叫notFull.signal()方法啟用阻塞執行緒
- //第二、 take執行緒取元素時,發現佇列已滿。則其取出元素後,也會呼叫notFull.signal()方法啟用阻塞執行緒
- while (count.get() == capacity) {
- notFull.await();
- }
- // 把元素 e 新增到佇列中(隊尾)
- enqueue(e);
- c = count.getAndIncrement();
- //發現佇列未滿,呼叫notFull.signal()啟用阻塞的put執行緒(可能存在)
- if (c + 1 < capacity)
- notFull.signal();
- } finally {
- putLock.unlock();
- }
- if (c == 0)
- //佇列空,說明已經有take執行緒陷入阻塞,故呼叫signalNotEmpty啟用阻塞的take執行緒
- signalNotEmpty();
- }
- /**
- * Creates a node and links it at end of queue.
- * @param x the item
- */
- privatevoid enqueue(E x) {
- // assert putLock.isHeldByCurrentThread();
- last = last.next = new Node<E>(x);
- }
[java] view plain copy print?
- 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;
- }
- /**
- * Removes a node from head of queue.
- * @return the node
- */
- private E dequeue() {
- // assert takeLock.isHeldByCurrentThread();
- 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;
- }
小結:take和put操作各有一把鎖,可並行讀取。
4 SynchronousQueue, ArrayBlockingQueue 和 LinkedBlockingQueue 效能對比
-
執行緒多(>20),Queue長度長(>30),使用LinkedBlockingQueue
-
執行緒少 (<20) ,Queue長度短 (<30) , 使用SynchronousQueue
當然,使用SynchronousQueue的時候不要忘記應用的擴充套件,如果將來需要進行擴充套件還是選擇LinkedBlockingQueue好,儘量把SynchronousQueue限制在特殊場景中使用。
-
少用ArrayBlcokingQueue,似乎沒找到它的好處,高手給給建議吧!
參考文章: