---
title: "Java多线程（六）之Deque与LinkedBlockingDeque深入分析"
author: "iaspecwang"
date: "2013-08-28T09:45:53Z"
tags: []
categories: ["编程语言"]
slug: "java-deque-linkedblockingdeque"
draft: false
lastmod: "2013-08-28T09:45:53Z"
id: 1931028
url: "https://iaspecwang.iteye.com/blog/1931028"
---

# 一、双向队列Deque

 

Queue除了前面介绍的实现外，还有一种双向的Queue实现Deque。这种队列允许在队列头和尾部进行入队出队操作，因此在功能上比Queue显然要更复杂。下图描述的是Deque的完整体系图。需要说明的是LinkedList也已经加入了Deque的一部分（LinkedList是从jdk1.2 开始就存在数据结构）。

 

![](http://img.my.csdn.net/uploads/201212/07/1354809676_3123.png)

Deque在Queue的基础上增加了更多的操作方法。

![](http://img.my.csdn.net/uploads/201212/07/1354809693_2460.png)

从上图可以看到，Deque不仅具有FIFO的Queue实现，也有FILO的实现，也就是不仅可以实现队列，也可以实现一个堆栈。

同时在Deque的体系结构图中可以看到，实现一个Deque可以使用数组（ArrayDeque），同时也可以使用链表（LinkedList），还可以同实现一个支持阻塞的线程安全版本队列LinkedBlockingDeque。

 

## []()1、ArrayDeque实现Deque

 

![](http://img.my.csdn.net/uploads/201212/07/1354809706_2576.png)

 

对于数组实现的Deque来说，数据结构上比较简单，只需要一个存储数据的数组以及头尾两个索引即可。由于数组是固定长度的，所以很容易就得到数组的头和尾，那么对于数组的操作只需要移动头和尾的索引即可。

特别说明的是ArrayDeque并不是一个固定大小的队列，每次队列满了以后就将队列容量扩大一倍（doubleCapacity()），因此加入一个元素总是能成功，而且也不会抛出一个异常。也就是说ArrayDeque是一个没有容量限制的队列。

同样继续性能的考虑，使用System.arraycopy复制一个数组比循环设置要高效得多。

 

### []()1.1、ArrayDeque的源码解析

 

 

**\[java]** [view plain](http://blog.csdn.net/vernonzheng/article/details/8267541 "view plain")[copy](http://blog.csdn.net/vernonzheng/article/details/8267541 "copy")

 

001. //数组双端队列ArrayDeque的源码解析
002. public class ArrayDeque&lt;E&gt; extends AbstractCollection&lt;E&gt; implements Deque&lt;E&gt;, Cloneable, Serializable{
003. /\**
004. * 存放队列元素的数组，数组的长度为“2的指数”
005. \*/
006. private transient E\[] elements;
007. /\**
008. \*队列的头部索引位置，（被remove（）或pop（）操作的位置），当为空队列时，首尾index相同
009. \*/
010. private transient int head;
011. /\**
012. * 队列的尾部索引位置，(被 addLast(E), add(E), 或 push(E)操作的位置).
013. \*/
014. private transient int tail;
015. /\**
016. * 队列的最小容量（大小必须为“2的指数”）
017. \*/
018. private static final int MIN\_INITIAL\_CAPACITY = 8;
019. // \*\*\*\*\**  Array allocation and resizing utilities \*\*\*\*\**
020. /\**
021. * 根据所给的数组长度，得到一个比该长度大的最小的2^p的真实长度，并建立真实长度的空数组
022. \*/
023. private void allocateElements(int numElements) {
024. int initialCapacity = MIN\_INITIAL\_CAPACITY;
025. if (numElements &gt;= initialCapacity) {
026. initialCapacity = numElements;
027. initialCapacity |= (initialCapacity &gt;&gt;&gt;  1);
028. initialCapacity |= (initialCapacity &gt;&gt;&gt;  2);
029. initialCapacity |= (initialCapacity &gt;&gt;&gt;  4);
030. initialCapacity |= (initialCapacity &gt;&gt;&gt;  8);
031. initialCapacity |= (initialCapacity &gt;&gt;&gt; 16);
032. initialCapacity++;
033. if (initialCapacity &lt; 0)   // Too many elements, must back off
034. initialCapacity &gt;&gt;&gt;= 1;// Good luck allocating 2 ^ 30 elements
035. }
036. elements = (E\[]) new Object\[initialCapacity];
037. }
038. /\**
039. * 当队列首尾指向同一个引用时，扩充队列的容量为原来的两倍，并对元素重新定位到新数组中
040. \*/
041. private void doubleCapacity() {
042. assert head == tail;
043. int p = head;
044. int n = elements.length;
045. int r = n - p; // number of elements to the right of p
046. int newCapacity = n &lt;&lt; 1;
047. if (newCapacity &lt; 0)
048. throw new IllegalStateException("Sorry, deque too big");
049. Object\[] a = new Object\[newCapacity];
050. System.arraycopy(elements, p, a, 0, r);
051. System.arraycopy(elements, 0, a, r, p);
052. elements = (E\[])a;
053. head = 0;
054. tail = n;
055. }
056. /\**
057. * 拷贝队列中的元素到新数组中
058. \*/
059. private &lt;T&gt; T\[] copyElements(T\[] a) {
060. if (head &lt; tail) {
061. System.arraycopy(elements, head, a, 0, size());
062. } else if (head &gt; tail) {
063. int headPortionLen = elements.length - head;
064. System.arraycopy(elements, head, a, 0, headPortionLen);
065. System.arraycopy(elements, 0, a, headPortionLen, tail);
066. }
067. return a;
068. }
069. /\**
070. * 默认构造队列，初始化一个长度为16的数组
071. \*/
072. public ArrayDeque() {
073. elements = (E\[]) new Object\[16];
074. }
075. /\**
076. * 指定元素个数的构造方法
077. \*/
078. public ArrayDeque(int numElements) {
079. allocateElements(numElements);
080. }
081. /\**
082. * 用一个集合作为参数的构造方法
083. \*/
084. public ArrayDeque(Collection&lt;? extends E&gt; c) {
085. allocateElements(c.size());
086. addAll(c);
087. }
088. //插入和删除的方法主要是： addFirst(),addLast(), pollFirst(), pollLast()。
089. //其他的方法依赖于这些实现。
090. /\**
091. * 在双端队列的前端插入元素,元素为null抛异常
092. \*/
093. public void addFirst(E e) {
094. if (e == null)
095. throw new NullPointerException();
096. elements\[head = (head - 1) & (elements.length - 1)] = e;
097. if (head == tail)
098. doubleCapacity();
099. }
100. /\**
101. \*在双端队列的末端插入元素，元素为null抛异常
102. \*/
103. public void addLast(E e) {
104. if (e == null)
105. throw new NullPointerException();
106. elements\[tail] = e;
107. if ( (tail = (tail + 1) & (elements.length - 1)) == head)
108. doubleCapacity();
109. }
110. /\**
111. * 在前端插入，调用addFirst实现，返回boolean类型
112. \*/
113. public boolean offerFirst(E e) {
114. addFirst(e);
115. return true;
116. }
117. /\**
118. * 在末端插入，调用addLast实现，返回boolean类型
119. \*/
120. public boolean offerLast(E e) {
121. addLast(e);
122. return true;
123. }
124. /\**
125. * 删除前端，调用pollFirst实现
126. \*/
127. public E removeFirst() {
128. E x = pollFirst();
129. if (x == null)
130. throw new NoSuchElementException();
131. return x;
132. }
133. /\**
134. * 删除后端，调用pollLast实现
135. \*/
136. public E removeLast() {
137. E x = pollLast();
138. if (x == null)
139. throw new NoSuchElementException();
140. return x;
141. }
142. //前端出对（删除前端）
143. public E pollFirst() {
144. int h = head;
145. E result = elements\[h]; // Element is null if deque empty
146. if (result == null)
147. return null;
148. elements\[h] = null;     // Must null out slot
149. head = (h + 1) & (elements.length - 1);
150. return result;
151. }
152. //后端出对（删除后端）
153. public E pollLast() {
154. int t = (tail - 1) & (elements.length - 1);
155. E result = elements\[t];
156. if (result == null)
157. return null;
158. elements\[t] = null;
159. tail = t;
160. return result;
161. }
162. /\**
163. * 得到前端头元素
164. \*/
165. public E getFirst() {
166. E x = elements\[head];
167. if (x == null)
168. throw new NoSuchElementException();
169. return x;
170. }
171. /\**
172. * 得到末端尾元素
173. \*/
174. public E getLast() {
175. E x = elements\[(tail - 1) & (elements.length - 1)];
176. if (x == null)
177. throw new NoSuchElementException();
178. return x;
179. }
180. public E peekFirst() {
181. return elements\[head]; // elements\[head] is null if deque empty
182. }
183. public E peekLast() {
184. return elements\[(tail - 1) & (elements.length - 1)];
185. }
186. /\**
187. * 移除此双端队列中第一次出现的指定元素（当从头部到尾部遍历双端队列时）。
188. \*/
189. public boolean removeFirstOccurrence(Object o) {
190. if (o == null)
191. return false;
192. int mask = elements.length - 1;
193. int i = head;
194. E x;
195. while ( (x = elements\[i]) != null) {
196. if (o.equals(x)) {
197. delete(i);
198. return true;
199. }
200. i = (i + 1) & mask;
201. }
202. return false;
203. }
204. /\**
205. * 移除此双端队列中最后一次出现的指定元素（当从头部到尾部遍历双端队列时）。
206. \*/
207. public boolean removeLastOccurrence(Object o) {
208. if (o == null)
209. return false;
210. int mask = elements.length - 1;
211. int i = (tail - 1) & mask;
212. E x;
213. while ( (x = elements\[i]) != null) {
214. if (o.equals(x)) {
215. delete(i);
216. return true;
217. }
218. i = (i - 1) & mask;
219. }
220. return false;
221. }
222. // \*\** 队列方法（Queue methods） \*\**
223. /\**
224. * add方法，添加到队列末端
225. \*/
226. public boolean add(E e) {
227. addLast(e);
228. return true;
229. }
230. /\**
231. * 同上
232. \*/
233. public boolean offer(E e) {
234. return offerLast(e);
235. }
236. /\**
237. * remove元素，删除队列前端
238. \*/
239. public E remove() {
240. return removeFirst();
241. }
242. /\**
243. * 弹出前端（出对，删除前端）
244. \*/
245. public E poll() {
246. return pollFirst();
247. }
248. public E element() {
249. return getFirst();
250. }
251. public E peek() {
252. return peekFirst();
253. }
254. // \*\** 栈 方法（Stack methods） \*\**
255. public void push(E e) {
256. addFirst(e);
257. }
258. public E pop() {
259. return removeFirst();
260. }
261. private void checkInvariants() { ……    }
262. private boolean delete(int i) {   ……   }
263. // \*\** 集合方法（Collection Methods） \*\**
264. ……
265. // \*\** Object methods \*\**
266. ……
267. }
268. 整体来说:1个数组，2个index（head 索引和tail索引）。实现比较简单，容易理解。

 

 

## []()2、LinkedList实现Deque

 

![](http://img.my.csdn.net/uploads/201212/07/1354809729_7889.png)

对于LinkedList本身而言，数据结构就更简单了，除了一个size用来记录大小外，只有head一个元素Entry。对比Map和Queue的其它数据结构可以看到这里的Entry有两个引用，是双向的队列。

在示意图中，LinkedList总是有一个“傀儡”节点，用来描述队列“头部”，但是并不表示头部元素，它是一个执行null的空节点。

队列一开始只有head一个空元素，然后从尾部加入E1(add/addLast)，head和E1之间建立双向链接。然后继续从尾部加入E2，E2就在head和E1之间建立双向链接。最后从队列的头部加入E3(push/addFirst)，于是E3就在E1和head之间链接双向链接。

双向链表的数据结构比较简单，操作起来也比较容易，从事从“傀儡”节点开始，“傀儡”节点的下一个元素就是队列的头部，前一个元素是队列的尾部，换句话说，“傀儡”节点在头部和尾部之间建立了一个通道，是整个队列形成一个循环，这样就可以从任意一个节点的任意一个方向能遍历完整的队列。

同样LinkedList也是一个没有容量限制的队列，因此入队列（不管是从头部还是尾部）总能成功。

 

## []()3、小结

 

上面描述的ArrayDeque和LinkedList是两种不同方式的实现，通常在遍历和节省内存上ArrayDeque更高效（索引更快，另外不需要Entry对象），但是在队列扩容下LinkedList更灵活，因为不需要复制原始的队列，某些情况下可能更高效。

同样需要注意的上述两个实现都不是线程安全的，因此只适合在单线程环境下使用，下面章节要介绍的LinkedBlockingDeque就是线程安全的可阻塞的Deque。事实上也应该是功能最强大的Queue实现，当然了实现起来也许会复杂一点。

 

# []()二、双向并发阻塞队列 LinkedBlockingDeque

 

## []()1、LinkedBlockingDeque数据结构

 

双向并发阻塞队列。所谓双向是指可以从队列的头和尾同时操作，并发只是线程安全的实现，阻塞允许在入队出队不满足条件时挂起线程，这里说的队列是指支持FIFO/FILO实现的链表。

 

首先看下LinkedBlockingDeque的数据结构。通常情况下从数据结构上就能看出这种实现的优缺点，这样就知道如何更好的使用工具了。

![](http://img.my.csdn.net/uploads/201212/07/1354809743_7567.png)

从数据结构和功能需求上可以得到以下结论：

1. 要想支持阻塞功能，队列的容量一定是固定的，否则无法在入队的时候挂起线程。也就是capacity是final类型的。
2. 既然是双向链表，每一个结点就需要前后两个引用，这样才能将所有元素串联起来，支持双向遍历。也即需要prev/next两个引用。
3. 双向链表需要头尾同时操作，所以需要first/last两个节点，当然可以参考LinkedList那样采用一个节点的双向来完成，那样实现起来就稍微麻烦点。
4. 既然要支持阻塞功能，就需要锁和条件变量来挂起线程。这里使用一个锁两个条件变量来完成此功能。

 

## []()2、LinkedBlockingDeque源码分析

 

 

**\[java]** [view plain](http://blog.csdn.net/vernonzheng/article/details/8267541 "view plain")[copy](http://blog.csdn.net/vernonzheng/article/details/8267541 "copy")

 

001. public class LinkedBlockingDeque&lt;E&gt; extends AbstractQueue&lt;E&gt; implements BlockingDeque&lt;E&gt;,  java.io.Serializable {
002. /\** 包含前驱和后继节点的双向链式结构 \*/
003. static final class Node&lt;E&gt; {
004. E item;
005. Node&lt;E&gt; prev;
006. Node&lt;E&gt; next;
007. Node(E x, Node&lt;E&gt; p, Node&lt;E&gt; n) {
008. item = x;
009. prev = p;
010. next = n;
011. }
012. }
013. /\** 头节点 \*/
014. private transient Node&lt;E&gt; first;
015. /\** 尾节点 \*/
016. private transient Node&lt;E&gt; last;
017. /\** 元素个数\*/
018. private transient int count;
019. /\** 队列容量 \*/
020. private final int capacity;
021. /\** 锁 \*/
022. private final ReentrantLock lock = new ReentrantLock();
023. /\** notEmpty条件 \*/
024. private final Condition notEmpty = lock.newCondition();
025. /\** notFull条件 \*/
026. private final Condition notFull = lock.newCondition();
027. /\** 构造方法 \*/
028. public LinkedBlockingDeque() {
029. this(Integer.MAX\_VALUE);
030. }
031. public LinkedBlockingDeque(int capacity) {
032. if (capacity &lt;= 0) throw new IllegalArgumentException();
033. this.capacity = capacity;
034. }
035. public LinkedBlockingDeque(Collection&lt;? extends E&gt; c) {
036. this(Integer.MAX\_VALUE);
037. for (E e : c)
038. add(e);
039. }
040. /\**
041. * 添加元素作为新的头节点
042. \*/
043. private boolean linkFirst(E e) {
044. if (count &gt;= capacity)
045. return false;
046. ++count;
047. Node&lt;E&gt; f = first;
048. Node&lt;E&gt; x = new Node&lt;E&gt;(e, null, f);
049. first = x;
050. if (last == null)
051. last = x;
052. else
053. f.prev = x;
054. notEmpty.signal();
055. return true;
056. }
057. /\**
058. * 添加尾元素
059. \*/
060. private boolean linkLast(E e) {
061. if (count &gt;= capacity)
062. return false;
063. ++count;
064. Node&lt;E&gt; l = last;
065. Node&lt;E&gt; x = new Node&lt;E&gt;(e, l, null);
066. last = x;
067. if (first == null)
068. first = x;
069. else
070. l.next = x;
071. notEmpty.signal();
072. return true;
073. }
074. /\**
075. * 返回并移除头节点
076. \*/
077. private E unlinkFirst() {
078. Node&lt;E&gt; f = first;
079. if (f == null)
080. return null;
081. Node&lt;E&gt; n = f.next;
082. first = n;
083. if (n == null)
084. last = null;
085. else
086. n.prev = null;
087. --count;
088. notFull.signal();
089. return f.item;
090. }
091. /\**
092. * 返回并移除尾节点
093. \*/
094. private E unlinkLast() {
095. Node&lt;E&gt; l = last;
096. if (l == null)
097. return null;
098. Node&lt;E&gt; p = l.prev;
099. last = p;
100. if (p == null)
101. first = null;
102. else
103. p.next = null;
104. --count;
105. notFull.signal();
106. return l.item;
107. }
108. /\**
109. * 移除节点x
110. \*/
111. private void unlink(Node&lt;E&gt; x) {
112. Node&lt;E&gt; p = x.prev;
113. Node&lt;E&gt; n = x.next;
114. if (p == null) {//x是头的情况
115. if (n == null)
116. first = last = null;
117. else {
118. n.prev = null;
119. first = n;
120. }
121. } else if (n == null) {//x是尾的情况
122. p.next = null;
123. last = p;
124. } else {//x是中间的情况
125. p.next = n;
126. n.prev = p;
127. }
128. --count;
129. notFull.signalAll();
130. }
131. //--------------------------------- BlockingDeque 双端阻塞队列方法实现
132. public void addFirst(E e) {
133. if (!offerFirst(e))
134. throw new IllegalStateException("Deque full");
135. }
136. public void addLast(E e) {
137. if (!offerLast(e))
138. throw new IllegalStateException("Deque full");
139. }
140. public boolean offerFirst(E e) {
141. if (e == null) throw new NullPointerException();
142. lock.lock();
143. try {
144. return linkFirst(e);
145. } finally {
146. lock.unlock();
147. }
148. }
149. public boolean offerLast(E e) {
150. if (e == null) throw new NullPointerException();
151. lock.lock();
152. try {
153. return linkLast(e);
154. } finally {
155. lock.unlock();
156. }
157. }
158. public void putFirst(E e) throws InterruptedException {
159. if (e == null) throw new NullPointerException();
160. lock.lock();
161. try {
162. while (!linkFirst(e))
163. notFull.await();
164. } finally {
165. lock.unlock();
166. }
167. }
168. public void putLast(E e) throws InterruptedException {
169. if (e == null) throw new NullPointerException();
170. lock.lock();
171. try {
172. while (!linkLast(e))
173. notFull.await();
174. } finally {
175. lock.unlock();
176. }
177. }
178. public boolean offerFirst(E e, long timeout, TimeUnit unit)
179. throws InterruptedException {
180. if (e == null) throw new NullPointerException();
181. long nanos = unit.toNanos(timeout);
182. lock.lockInterruptibly();
183. try {
184. for (;;) {
185. if (linkFirst(e))
186. return true;
187. if (nanos &lt;= 0)
188. return false;
189. nanos = notFull.awaitNanos(nanos);
190. }
191. } finally {
192. lock.unlock();
193. }
194. }
195. public boolean offerLast(E e, long timeout, TimeUnit unit)
196. throws InterruptedException {
197. if (e == null) throw new NullPointerException();
198. long nanos = unit.toNanos(timeout);
199. lock.lockInterruptibly();
200. try {
201. for (;;) {
202. if (linkLast(e))
203. return true;
204. if (nanos &lt;= 0)
205. return false;
206. nanos = notFull.awaitNanos(nanos);
207. }
208. } finally {
209. lock.unlock();
210. }
211. }
212. public E removeFirst() {
213. E x = pollFirst();
214. if (x == null) throw new NoSuchElementException();
215. return x;
216. }
217. public E removeLast() {
218. E x = pollLast();
219. if (x == null) throw new NoSuchElementException();
220. return x;
221. }
222. public E pollFirst() {
223. lock.lock();
224. try {
225. return unlinkFirst();
226. } finally {
227. lock.unlock();
228. }
229. }
230. public E pollLast() {
231. lock.lock();
232. try {
233. return unlinkLast();
234. } finally {
235. lock.unlock();
236. }
237. }
238. public E takeFirst() throws InterruptedException {
239. lock.lock();
240. try {
241. E x;
242. while ( (x = unlinkFirst()) == null)
243. notEmpty.await();
244. return x;
245. } finally {
246. lock.unlock();
247. }
248. }
249. public E takeLast() throws InterruptedException {
250. lock.lock();
251. try {
252. E x;
253. while ( (x = unlinkLast()) == null)
254. notEmpty.await();
255. return x;
256. } finally {
257. lock.unlock();
258. }
259. }
260. public E pollFirst(long timeout, TimeUnit unit)
261. throws InterruptedException {
262. long nanos = unit.toNanos(timeout);
263. lock.lockInterruptibly();
264. try {
265. for (;;) {
266. E x = unlinkFirst();
267. if (x != null)
268. return x;
269. if (nanos &lt;= 0)
270. return null;
271. nanos = notEmpty.awaitNanos(nanos);
272. }
273. } finally {
274. lock.unlock();
275. }
276. }
277. public E pollLast(long timeout, TimeUnit unit)
278. throws InterruptedException {
279. long nanos = unit.toNanos(timeout);
280. lock.lockInterruptibly();
281. try {
282. for (;;) {
283. E x = unlinkLast();
284. if (x != null)
285. return x;
286. if (nanos &lt;= 0)
287. return null;
288. nanos = notEmpty.awaitNanos(nanos);
289. }
290. } finally {
291. lock.unlock();
292. }
293. }
294. public E getFirst() {
295. E x = peekFirst();
296. if (x == null) throw new NoSuchElementException();
297. return x;
298. }
299. public E getLast() {
300. E x = peekLast();
301. if (x == null) throw new NoSuchElementException();
302. return x;
303. }
304. public E peekFirst() {
305. lock.lock();
306. try {
307. return (first == null) ? null : first.item;
308. } finally {
309. lock.unlock();
310. }
311. }
312. public E peekLast() {
313. lock.lock();
314. try {
315. return (last == null) ? null : last.item;
316. } finally {
317. lock.unlock();
318. }
319. }
320. public boolean removeFirstOccurrence(Object o) {
321. if (o == null) return false;
322. lock.lock();
323. try {
324. for (Node&lt;E&gt; p = first; p != null; p = p.next) {
325. if (o.equals(p.item)) {
326. unlink(p);
327. return true;
328. }
329. }
330. return false;
331. } finally {
332. lock.unlock();
333. }
334. }
335. public boolean removeLastOccurrence(Object o) {
336. if (o == null) return false;
337. lock.lock();
338. try {
339. for (Node&lt;E&gt; p = last; p != null; p = p.prev) {
340. if (o.equals(p.item)) {
341. unlink(p);
342. return true;
343. }
344. }
345. return false;
346. } finally {
347. lock.unlock();
348. }
349. }
350. //---------------------------------- BlockingQueue阻塞队列 方法实现
351. public boolean add(E e) {
352. addLast(e);
353. return true;
354. }
355. public boolean offer(E e) {
356. return offerLast(e);
357. }
358. public void put(E e) throws InterruptedException {
359. putLast(e);
360. }
361. public boolean offer(E e, long timeout, TimeUnit unit)
362. throws InterruptedException {
363. return offerLast(e, timeout, unit);
364. }
365. public E remove() {
366. return removeFirst();
367. }
368. public E poll() {
369. return pollFirst();
370. }
371. public E take() throws InterruptedException {
372. return takeFirst();
373. }
374. public E poll(long timeout, TimeUnit unit) throws InterruptedException {
375. return pollFirst(timeout, unit);
376. }
377. public E element() {
378. return getFirst();
379. }
380. public E peek() {
381. return peekFirst();
382. }
383. //------------------------------------------- Stack 方法实现
384. public void push(E e) {
385. addFirst(e);
386. }
387. public E pop() {
388. return removeFirst();
389. }
390. //------------------------------------------- Collection 方法实现
391. public boolean remove(Object o) {
392. return removeFirstOccurrence(o);
393. }
394. public int size() {
395. lock.lock();
396. try {
397. return count;
398. } finally {
399. lock.unlock();
400. }
401. }
402. public boolean contains(Object o) {
403. if (o == null) return false;
404. lock.lock();
405. try {
406. for (Node&lt;E&gt; p = first; p != null; p = p.next)
407. if (o.equals(p.item))
408. return true;
409. return false;
410. } finally {
411. lock.unlock();
412. }
413. }
414. boolean removeNode(Node&lt;E&gt; e) {
415. lock.lock();
416. try {
417. for (Node&lt;E&gt; p = first; p != null; p = p.next) {
418. if (p == e) {
419. unlink(p);
420. return true;
421. }
422. }
423. return false;
424. } finally {
425. lock.unlock();
426. }
427. }
428. ……
429. }

 

## []()3、LinkedBlockingDeque的优缺点

 

有了上面的结论再来研究LinkedBlockingDeque的优缺点。

优点当然是功能足够强大，同时由于采用一个独占锁，因此实现起来也比较简单。所有对队列的操作都加锁就可以完成。同时独占锁也能够很好的支持双向阻塞的特性。

凡事有利必有弊。缺点就是由于独占锁，所以不能同时进行两个操作，这样性能上就大打折扣。从性能的角度讲LinkedBlockingDeque要比LinkedBlockingQueue要低很多，比CocurrentLinkedQueue就低更多了，这在高并发情况下就比较明显了。

前面分析足够多的Queue实现后，LinkedBlockingDeque的原理和实现就不值得一提了，无非是在独占锁下对一个链表的普通操作。

 

## []()4、LinkedBlockingDeque的序列化、反序列化

 

有趣的是此类支持序列化，但是Node并不支持序列化，因此fist/last就不能序列化，那么如何完成序列化/反序列化过程呢？

清单4 LinkedBlockingDeque的序列化、反序列化

> **\[java]** [view plain](http://blog.csdn.net/vernonzheng/article/details/8267541 "view plain")[copy](http://blog.csdn.net/vernonzheng/article/details/8267541 "copy")
> 
>  
> 
> 01. &lt;span style="font-size:14px;"&gt;private void writeObject(java.io.ObjectOutputStream s)
> 02. throws java.io.IOException {
> 03. lock.lock();
> 04. try {
> 05. // Write out capacity and any hidden stuff
> 06. s.defaultWriteObject();
> 07. // Write out all elements in the proper order.
> 08. for (Node&lt;E&gt; p = first; p != null; p = p.next)
> 09. s.writeObject(p.item);
> 10. // Use trailing null as sentinel
> 11. s.writeObject(null);
> 12. } finally {
> 13. lock.unlock();
> 14. }
> 15. }
> 16. private void readObject(java.io.ObjectInputStream s)
> 17. throws java.io.IOException, ClassNotFoundException {
> 18. s.defaultReadObject();
> 19. count = 0;
> 20. first = null;
> 21. last = null;
> 22. // Read in all elements and place in queue
> 23. for (;;) {
> 24. E item = (E)s.readObject();
> 25. if (item == null)
> 26. break;
> 27. add(item);
> 28. }
> 29. }
> 30. &lt;/span&gt;

清单4 描述的是LinkedBlockingDeque序列化/反序列化的过程。序列化时将真正的元素写入输出流，最后还写入了一个null。读取的时候将所有对象列表读出来，如果读取到一个null就表示结束。这就是为什么写入的时候写入一个null的原因，因为没有将count写入流，所以就靠null来表示结束，省一个整数空间。