1.1 簡介
LinkedBlockingQueue是一個由鏈表結(jié)構(gòu)組成的有界阻塞隊列皂贩,此隊列是FIFO(先進先出)的順序來訪問的蝌矛,它由隊尾插入后再從隊頭取出或移除碎罚,其中隊列的頭部是在隊列中時間最長的元素欣硼,隊列的尾部是在隊列中時間最短的元素混卵。在LinkedBlockingQueue類中分別用2個不同的鎖takeLock映穗、putLock來保護隊頭和隊尾操作。如下圖所示:
image
1.2 類圖
image
1.3 源碼分析
1.3.1 屬性與鏈表節(jié)點類
//鏈表節(jié)點類幕随,next指向下一個節(jié)點蚁滋。如果下一個節(jié)點時null表示沒有節(jié)點了。
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
// 最大容量上限赘淮,默認是 Integer.MAX_VALUE
private final int capacity;
// 當前元素數(shù)量辕录,這是個原子類。
private final AtomicInteger count = new AtomicInteger(0);
// 頭結(jié)點
private transient Node<E> head;
// 尾結(jié)點
private transient Node<E> last;
// 隊頭訪問鎖
private final ReentrantLock takeLock = new ReentrantLock();
// 隊頭訪問等待條件梢卸、隊列
private final Condition notEmpty = takeLock.newCondition();
// 隊尾訪問鎖
private final ReentrantLock putLock = new ReentrantLock();
// 隊尾訪問等待條件走诞、隊列
private final Condition notFull = putLock.newCondition();
使用原子類AtomicInteger是因為讀寫分別使用了不同的鎖,但都會訪問這個屬性來計算隊列中元素的數(shù)量蛤高,所以它需要是線程安全的速梗。關(guān)AtomicInteger詳細請看我的這一篇文章:【Java并發(fā)編程】深入分析AtomicInteger(二)
1.3.2 offer操作
public boolean offer(E e) {
if (e == null) throw new NullPointerException();
final AtomicInteger count = this.count;
//當隊列滿時,直接返回了false襟齿,沒有被阻塞等待元素插入
if (count.get() == capacity)
return false;
int c = -1;
Node<E> node = new Node(e);
//開啟隊尾保護鎖
final ReentrantLock putLock = this.putLock;
putLock.lock();
try {
if (count.get() < capacity) {
enqueue(node);
//原則計數(shù)類
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
}
} finally {
//釋放鎖
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
return c >= 0;
}
//在持有鎖下指向下一個節(jié)點
private void enqueue(Node<E> node) {
// assert putLock.isHeldByCurrentThread();
// assert last.next == null;
last = last.next = node;
}
1.3.3 put操作
//put 操作把指定元素添加到隊尾姻锁,如果沒有空間則一直等待。
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.
//注釋:在所有的 put/take/etc等操作中變量c為負數(shù)表示失敗猜欺,>=0表示成功位隶。
int c = -1;
Node<E> node = new Node(e);
final ReentrantLock putLock = this.putLock;
final AtomicInteger count = this.count;
putLock.lockInterruptibly();
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.
*/
/*
* 注意,count用于等待監(jiān)視开皿,即使它沒有用鎖保護涧黄。這個可行是因為
* count 只能在此刻(持有putLock)減小(其他put線程都被鎖拒之門外)赋荆,
* 當count對capacity發(fā)生變化時笋妥,當前線程(或其他put等待線程)將被通知。
* 在其他等待監(jiān)視的使用中也類似窄潭。
*/
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
// 還有可添加空間則喚醒put等待線程春宣。
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
1.3.4 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;
}
//在持有鎖下返回隊列隊頭第一個節(jié)點
private E dequeue() {
// assert takeLock.isHeldByCurrentThread();
// assert head.item == null;
Node<E> h = head;
Node<E> first = h.next;
h.next = h; // help GC
//出隊后的節(jié)點作為頭節(jié)點并將元素置空
head = first;
E x = first.item;
first.item = null;
return x;
}
1.3.5 remove操作
image
//移除指定元素。
public boolean remove(Object o) {
if (o == null) return false;
//對兩把鎖加鎖
fullyLock();
try {
for (Node<E> trail = head, p = trail.next;
p != null;
trail = p, p = p.next) {
if (o.equals(p.item)) {
unlink(p, trail);
return true;
}
}
return false;
} finally {
fullyUnlock();
}
}
//p是移除元素所在節(jié)點幽污,trail是移除元素的上一個節(jié)點
void unlink(Node<E> p, Node<E> trail) {
// assert isFullyLocked();
// p.next is not changed, to allow iterators that are
// traversing p to maintain their weak-consistency guarantee.
p.item = null;
//將trail下一個節(jié)點指向p的下一個節(jié)點
trail.next = p.next;
if (last == p)
last = trail;
if (count.getAndDecrement() == capacity)
notFull.signal();
}
void fullyLock() {
putLock.lock();
takeLock.lock();
}
//釋放鎖時確保和加鎖順序一致
void fullyUnlock() {
takeLock.unlock();
putLock.unlock();
}
注意嚷辅,鎖的釋放順序與加鎖順序是相反的。
作者:小毛驢距误,一個Java游戲服務(wù)器開發(fā)者 原文地址:https://liulongling.github.io/