• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Written by Doug Lea with assistance from members of JCP JSR-166
3  * Expert Group and released to the public domain, as explained at
4  * http://creativecommons.org/publicdomain/zero/1.0/
5  * Other contributors include Andrew Wright, Jeffrey Hayes,
6  * Pat Fisher, Mike Judd.
7  */
8 
9 package jsr166;
10 
11 import static java.util.concurrent.TimeUnit.MILLISECONDS;
12 
13 import java.util.ArrayList;
14 import java.util.Arrays;
15 import java.util.Collection;
16 import java.util.Iterator;
17 import java.util.NoSuchElementException;
18 import java.util.Queue;
19 import java.util.concurrent.BlockingQueue;
20 import java.util.concurrent.CountDownLatch;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.ExecutorService;
23 import java.util.concurrent.LinkedBlockingQueue;
24 
25 import junit.framework.Test;
26 
27 public class LinkedBlockingQueueTest extends JSR166TestCase {
28 
29     // android-note: These tests have been moved into their own separate
30     // classes to work around CTS issues.
31     //
32     // public static class Unbounded extends BlockingQueueTest {
33     //    protected BlockingQueue emptyCollection() {
34     //        return new LinkedBlockingQueue();
35     //     }
36     // }
37     //
38     // public static class Bounded extends BlockingQueueTest {
39     //    protected BlockingQueue emptyCollection() {
40     //         return new LinkedBlockingQueue(SIZE);
41     //     }
42     // }
43     //
44     // public static void main(String[] args) {
45     //    main(suite(), args);
46     // }
47     //
48     // public static Test suite() {
49     //     return newTestSuite(LinkedBlockingQueueTest.class,
50     //                         new Unbounded().testSuite(),
51     //                         new Bounded().testSuite());
52     // }
53 
54     /**
55      * Returns a new queue of given size containing consecutive
56      * Integers 0 ... n.
57      */
populatedQueue(int n)58     private LinkedBlockingQueue<Integer> populatedQueue(int n) {
59         LinkedBlockingQueue<Integer> q =
60             new LinkedBlockingQueue<Integer>(n);
61         assertTrue(q.isEmpty());
62         for (int i = 0; i < n; i++)
63             assertTrue(q.offer(new Integer(i)));
64         assertFalse(q.isEmpty());
65         assertEquals(0, q.remainingCapacity());
66         assertEquals(n, q.size());
67         return q;
68     }
69 
70     /**
71      * A new queue has the indicated capacity, or Integer.MAX_VALUE if
72      * none given
73      */
testConstructor1()74     public void testConstructor1() {
75         assertEquals(SIZE, new LinkedBlockingQueue(SIZE).remainingCapacity());
76         assertEquals(Integer.MAX_VALUE, new LinkedBlockingQueue().remainingCapacity());
77     }
78 
79     /**
80      * Constructor throws IllegalArgumentException if capacity argument nonpositive
81      */
testConstructor2()82     public void testConstructor2() {
83         try {
84             new LinkedBlockingQueue(0);
85             shouldThrow();
86         } catch (IllegalArgumentException success) {}
87     }
88 
89     /**
90      * Initializing from null Collection throws NullPointerException
91      */
testConstructor3()92     public void testConstructor3() {
93         try {
94             new LinkedBlockingQueue(null);
95             shouldThrow();
96         } catch (NullPointerException success) {}
97     }
98 
99     /**
100      * Initializing from Collection of null elements throws NullPointerException
101      */
testConstructor4()102     public void testConstructor4() {
103         Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
104         try {
105             new LinkedBlockingQueue(elements);
106             shouldThrow();
107         } catch (NullPointerException success) {}
108     }
109 
110     /**
111      * Initializing from Collection with some null elements throws
112      * NullPointerException
113      */
testConstructor5()114     public void testConstructor5() {
115         Integer[] ints = new Integer[SIZE];
116         for (int i = 0; i < SIZE-1; ++i)
117             ints[i] = new Integer(i);
118         Collection<Integer> elements = Arrays.asList(ints);
119         try {
120             new LinkedBlockingQueue(elements);
121             shouldThrow();
122         } catch (NullPointerException success) {}
123     }
124 
125     /**
126      * Queue contains all elements of collection used to initialize
127      */
testConstructor6()128     public void testConstructor6() {
129         Integer[] ints = new Integer[SIZE];
130         for (int i = 0; i < SIZE; ++i)
131             ints[i] = new Integer(i);
132         LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
133         for (int i = 0; i < SIZE; ++i)
134             assertEquals(ints[i], q.poll());
135     }
136 
137     /**
138      * Queue transitions from empty to full when elements added
139      */
testEmptyFull()140     public void testEmptyFull() {
141         LinkedBlockingQueue q = new LinkedBlockingQueue(2);
142         assertTrue(q.isEmpty());
143         assertEquals("should have room for 2", 2, q.remainingCapacity());
144         q.add(one);
145         assertFalse(q.isEmpty());
146         q.add(two);
147         assertFalse(q.isEmpty());
148         assertEquals(0, q.remainingCapacity());
149         assertFalse(q.offer(three));
150     }
151 
152     /**
153      * remainingCapacity decreases on add, increases on remove
154      */
testRemainingCapacity()155     public void testRemainingCapacity() {
156         BlockingQueue q = populatedQueue(SIZE);
157         for (int i = 0; i < SIZE; ++i) {
158             assertEquals(i, q.remainingCapacity());
159             assertEquals(SIZE, q.size() + q.remainingCapacity());
160             assertEquals(i, q.remove());
161         }
162         for (int i = 0; i < SIZE; ++i) {
163             assertEquals(SIZE-i, q.remainingCapacity());
164             assertEquals(SIZE, q.size() + q.remainingCapacity());
165             assertTrue(q.add(i));
166         }
167     }
168 
169     /**
170      * Offer succeeds if not full; fails if full
171      */
testOffer()172     public void testOffer() {
173         LinkedBlockingQueue q = new LinkedBlockingQueue(1);
174         assertTrue(q.offer(zero));
175         assertFalse(q.offer(one));
176     }
177 
178     /**
179      * add succeeds if not full; throws IllegalStateException if full
180      */
testAdd()181     public void testAdd() {
182         LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
183         for (int i = 0; i < SIZE; ++i)
184             assertTrue(q.add(new Integer(i)));
185         assertEquals(0, q.remainingCapacity());
186         try {
187             q.add(new Integer(SIZE));
188             shouldThrow();
189         } catch (IllegalStateException success) {}
190     }
191 
192     /**
193      * addAll(this) throws IllegalArgumentException
194      */
testAddAllSelf()195     public void testAddAllSelf() {
196         LinkedBlockingQueue q = populatedQueue(SIZE);
197         try {
198             q.addAll(q);
199             shouldThrow();
200         } catch (IllegalArgumentException success) {}
201     }
202 
203     /**
204      * addAll of a collection with any null elements throws NPE after
205      * possibly adding some elements
206      */
testAddAll3()207     public void testAddAll3() {
208         LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
209         Integer[] ints = new Integer[SIZE];
210         for (int i = 0; i < SIZE-1; ++i)
211             ints[i] = new Integer(i);
212         Collection<Integer> elements = Arrays.asList(ints);
213         try {
214             q.addAll(elements);
215             shouldThrow();
216         } catch (NullPointerException success) {}
217     }
218 
219     /**
220      * addAll throws IllegalStateException if not enough room
221      */
testAddAll4()222     public void testAddAll4() {
223         LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE - 1);
224         Integer[] ints = new Integer[SIZE];
225         for (int i = 0; i < SIZE; ++i)
226             ints[i] = new Integer(i);
227         Collection<Integer> elements = Arrays.asList(ints);
228         try {
229             q.addAll(elements);
230             shouldThrow();
231         } catch (IllegalStateException success) {}
232     }
233 
234     /**
235      * Queue contains all elements, in traversal order, of successful addAll
236      */
testAddAll5()237     public void testAddAll5() {
238         Integer[] empty = new Integer[0];
239         Integer[] ints = new Integer[SIZE];
240         for (int i = 0; i < SIZE; ++i)
241             ints[i] = new Integer(i);
242         LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
243         assertFalse(q.addAll(Arrays.asList(empty)));
244         assertTrue(q.addAll(Arrays.asList(ints)));
245         for (int i = 0; i < SIZE; ++i)
246             assertEquals(ints[i], q.poll());
247     }
248 
249     /**
250      * all elements successfully put are contained
251      */
testPut()252     public void testPut() throws InterruptedException {
253         LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
254         for (int i = 0; i < SIZE; ++i) {
255             Integer x = new Integer(i);
256             q.put(x);
257             assertTrue(q.contains(x));
258         }
259         assertEquals(0, q.remainingCapacity());
260     }
261 
262     /**
263      * put blocks interruptibly if full
264      */
testBlockingPut()265     public void testBlockingPut() throws InterruptedException {
266         final LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
267         final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
268         Thread t = newStartedThread(new CheckedRunnable() {
269             public void realRun() throws InterruptedException {
270                 for (int i = 0; i < SIZE; ++i)
271                     q.put(i);
272                 assertEquals(SIZE, q.size());
273                 assertEquals(0, q.remainingCapacity());
274 
275                 Thread.currentThread().interrupt();
276                 try {
277                     q.put(99);
278                     shouldThrow();
279                 } catch (InterruptedException success) {}
280                 assertFalse(Thread.interrupted());
281 
282                 pleaseInterrupt.countDown();
283                 try {
284                     q.put(99);
285                     shouldThrow();
286                 } catch (InterruptedException success) {}
287                 assertFalse(Thread.interrupted());
288             }});
289 
290         await(pleaseInterrupt);
291         assertThreadStaysAlive(t);
292         t.interrupt();
293         awaitTermination(t);
294         assertEquals(SIZE, q.size());
295         assertEquals(0, q.remainingCapacity());
296     }
297 
298     /**
299      * put blocks interruptibly waiting for take when full
300      */
testPutWithTake()301     public void testPutWithTake() throws InterruptedException {
302         final int capacity = 2;
303         final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
304         final CountDownLatch pleaseTake = new CountDownLatch(1);
305         final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
306         Thread t = newStartedThread(new CheckedRunnable() {
307             public void realRun() throws InterruptedException {
308                 for (int i = 0; i < capacity; i++)
309                     q.put(i);
310                 pleaseTake.countDown();
311                 q.put(86);
312 
313                 pleaseInterrupt.countDown();
314                 try {
315                     q.put(99);
316                     shouldThrow();
317                 } catch (InterruptedException success) {}
318                 assertFalse(Thread.interrupted());
319             }});
320 
321         await(pleaseTake);
322         assertEquals(0, q.remainingCapacity());
323         assertEquals(0, q.take());
324 
325         await(pleaseInterrupt);
326         assertThreadStaysAlive(t);
327         t.interrupt();
328         awaitTermination(t);
329         assertEquals(0, q.remainingCapacity());
330     }
331 
332     /**
333      * timed offer times out if full and elements not taken
334      */
testTimedOffer()335     public void testTimedOffer() {
336         final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
337         final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
338         Thread t = newStartedThread(new CheckedRunnable() {
339             public void realRun() throws InterruptedException {
340                 q.put(new Object());
341                 q.put(new Object());
342                 long startTime = System.nanoTime();
343                 assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
344                 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
345                 pleaseInterrupt.countDown();
346                 try {
347                     q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
348                     shouldThrow();
349                 } catch (InterruptedException success) {}
350             }});
351 
352         await(pleaseInterrupt);
353         assertThreadStaysAlive(t);
354         t.interrupt();
355         awaitTermination(t);
356     }
357 
358     /**
359      * take retrieves elements in FIFO order
360      */
testTake()361     public void testTake() throws InterruptedException {
362         LinkedBlockingQueue q = populatedQueue(SIZE);
363         for (int i = 0; i < SIZE; ++i) {
364             assertEquals(i, q.take());
365         }
366     }
367 
368     /**
369      * Take removes existing elements until empty, then blocks interruptibly
370      */
testBlockingTake()371     public void testBlockingTake() throws InterruptedException {
372         final BlockingQueue q = populatedQueue(SIZE);
373         final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
374         Thread t = newStartedThread(new CheckedRunnable() {
375             public void realRun() throws InterruptedException {
376                 for (int i = 0; i < SIZE; ++i) {
377                     assertEquals(i, q.take());
378                 }
379 
380                 Thread.currentThread().interrupt();
381                 try {
382                     q.take();
383                     shouldThrow();
384                 } catch (InterruptedException success) {}
385                 assertFalse(Thread.interrupted());
386 
387                 pleaseInterrupt.countDown();
388                 try {
389                     q.take();
390                     shouldThrow();
391                 } catch (InterruptedException success) {}
392                 assertFalse(Thread.interrupted());
393             }});
394 
395         await(pleaseInterrupt);
396         assertThreadStaysAlive(t);
397         t.interrupt();
398         awaitTermination(t);
399     }
400 
401     /**
402      * poll succeeds unless empty
403      */
testPoll()404     public void testPoll() {
405         LinkedBlockingQueue q = populatedQueue(SIZE);
406         for (int i = 0; i < SIZE; ++i) {
407             assertEquals(i, q.poll());
408         }
409         assertNull(q.poll());
410     }
411 
412     /**
413      * timed poll with zero timeout succeeds when non-empty, else times out
414      */
testTimedPoll0()415     public void testTimedPoll0() throws InterruptedException {
416         LinkedBlockingQueue q = populatedQueue(SIZE);
417         for (int i = 0; i < SIZE; ++i) {
418             assertEquals(i, q.poll(0, MILLISECONDS));
419         }
420         assertNull(q.poll(0, MILLISECONDS));
421     }
422 
423     /**
424      * timed poll with nonzero timeout succeeds when non-empty, else times out
425      */
testTimedPoll()426     public void testTimedPoll() throws InterruptedException {
427         LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
428         for (int i = 0; i < SIZE; ++i) {
429             long startTime = System.nanoTime();
430             assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
431             assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
432         }
433         long startTime = System.nanoTime();
434         assertNull(q.poll(timeoutMillis(), MILLISECONDS));
435         assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
436         checkEmpty(q);
437     }
438 
439     /**
440      * Interrupted timed poll throws InterruptedException instead of
441      * returning timeout status
442      */
testInterruptedTimedPoll()443     public void testInterruptedTimedPoll() throws InterruptedException {
444         final BlockingQueue<Integer> q = populatedQueue(SIZE);
445         final CountDownLatch aboutToWait = new CountDownLatch(1);
446         Thread t = newStartedThread(new CheckedRunnable() {
447             public void realRun() throws InterruptedException {
448                 for (int i = 0; i < SIZE; ++i) {
449                     long t0 = System.nanoTime();
450                     assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
451                     assertTrue(millisElapsedSince(t0) < SMALL_DELAY_MS);
452                 }
453                 long t0 = System.nanoTime();
454                 aboutToWait.countDown();
455                 try {
456                     q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
457                     shouldThrow();
458                 } catch (InterruptedException success) {
459                     assertTrue(millisElapsedSince(t0) < MEDIUM_DELAY_MS);
460                 }
461             }});
462 
463         aboutToWait.await();
464         waitForThreadToEnterWaitState(t, SMALL_DELAY_MS);
465         t.interrupt();
466         awaitTermination(t, MEDIUM_DELAY_MS);
467         checkEmpty(q);
468     }
469 
470     /**
471      * peek returns next element, or null if empty
472      */
testPeek()473     public void testPeek() {
474         LinkedBlockingQueue q = populatedQueue(SIZE);
475         for (int i = 0; i < SIZE; ++i) {
476             assertEquals(i, q.peek());
477             assertEquals(i, q.poll());
478             assertTrue(q.peek() == null ||
479                        !q.peek().equals(i));
480         }
481         assertNull(q.peek());
482     }
483 
484     /**
485      * element returns next element, or throws NSEE if empty
486      */
testElement()487     public void testElement() {
488         LinkedBlockingQueue q = populatedQueue(SIZE);
489         for (int i = 0; i < SIZE; ++i) {
490             assertEquals(i, q.element());
491             assertEquals(i, q.poll());
492         }
493         try {
494             q.element();
495             shouldThrow();
496         } catch (NoSuchElementException success) {}
497     }
498 
499     /**
500      * remove removes next element, or throws NSEE if empty
501      */
testRemove()502     public void testRemove() {
503         LinkedBlockingQueue q = populatedQueue(SIZE);
504         for (int i = 0; i < SIZE; ++i) {
505             assertEquals(i, q.remove());
506         }
507         try {
508             q.remove();
509             shouldThrow();
510         } catch (NoSuchElementException success) {}
511     }
512 
513     /**
514      * An add following remove(x) succeeds
515      */
testRemoveElementAndAdd()516     public void testRemoveElementAndAdd() throws InterruptedException {
517         LinkedBlockingQueue q = new LinkedBlockingQueue();
518         assertTrue(q.add(new Integer(1)));
519         assertTrue(q.add(new Integer(2)));
520         assertTrue(q.remove(new Integer(1)));
521         assertTrue(q.remove(new Integer(2)));
522         assertTrue(q.add(new Integer(3)));
523         assertNotNull(q.take());
524     }
525 
526     /**
527      * contains(x) reports true when elements added but not yet removed
528      */
testContains()529     public void testContains() {
530         LinkedBlockingQueue q = populatedQueue(SIZE);
531         for (int i = 0; i < SIZE; ++i) {
532             assertTrue(q.contains(new Integer(i)));
533             q.poll();
534             assertFalse(q.contains(new Integer(i)));
535         }
536     }
537 
538     /**
539      * clear removes all elements
540      */
testClear()541     public void testClear() {
542         LinkedBlockingQueue q = populatedQueue(SIZE);
543         q.clear();
544         assertTrue(q.isEmpty());
545         assertEquals(0, q.size());
546         assertEquals(SIZE, q.remainingCapacity());
547         q.add(one);
548         assertFalse(q.isEmpty());
549         assertTrue(q.contains(one));
550         q.clear();
551         assertTrue(q.isEmpty());
552     }
553 
554     /**
555      * containsAll(c) is true when c contains a subset of elements
556      */
testContainsAll()557     public void testContainsAll() {
558         LinkedBlockingQueue q = populatedQueue(SIZE);
559         LinkedBlockingQueue p = new LinkedBlockingQueue(SIZE);
560         for (int i = 0; i < SIZE; ++i) {
561             assertTrue(q.containsAll(p));
562             assertFalse(p.containsAll(q));
563             p.add(new Integer(i));
564         }
565         assertTrue(p.containsAll(q));
566     }
567 
568     /**
569      * retainAll(c) retains only those elements of c and reports true if changed
570      */
testRetainAll()571     public void testRetainAll() {
572         LinkedBlockingQueue q = populatedQueue(SIZE);
573         LinkedBlockingQueue p = populatedQueue(SIZE);
574         for (int i = 0; i < SIZE; ++i) {
575             boolean changed = q.retainAll(p);
576             if (i == 0)
577                 assertFalse(changed);
578             else
579                 assertTrue(changed);
580 
581             assertTrue(q.containsAll(p));
582             assertEquals(SIZE-i, q.size());
583             p.remove();
584         }
585     }
586 
587     /**
588      * removeAll(c) removes only those elements of c and reports true if changed
589      */
testRemoveAll()590     public void testRemoveAll() {
591         for (int i = 1; i < SIZE; ++i) {
592             LinkedBlockingQueue q = populatedQueue(SIZE);
593             LinkedBlockingQueue p = populatedQueue(i);
594             assertTrue(q.removeAll(p));
595             assertEquals(SIZE-i, q.size());
596             for (int j = 0; j < i; ++j) {
597                 Integer x = (Integer)(p.remove());
598                 assertFalse(q.contains(x));
599             }
600         }
601     }
602 
603     /**
604      * toArray contains all elements in FIFO order
605      */
testToArray()606     public void testToArray() {
607         LinkedBlockingQueue q = populatedQueue(SIZE);
608         Object[] o = q.toArray();
609         for (int i = 0; i < o.length; i++)
610             assertSame(o[i], q.poll());
611     }
612 
613     /**
614      * toArray(a) contains all elements in FIFO order
615      */
testToArray2()616     public void testToArray2() throws InterruptedException {
617         LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
618         Integer[] ints = new Integer[SIZE];
619         Integer[] array = q.toArray(ints);
620         assertSame(ints, array);
621         for (int i = 0; i < ints.length; i++)
622             assertSame(ints[i], q.poll());
623     }
624 
625     /**
626      * toArray(incompatible array type) throws ArrayStoreException
627      */
testToArray1_BadArg()628     public void testToArray1_BadArg() {
629         LinkedBlockingQueue q = populatedQueue(SIZE);
630         try {
631             q.toArray(new String[10]);
632             shouldThrow();
633         } catch (ArrayStoreException success) {}
634     }
635 
636     /**
637      * iterator iterates through all elements
638      */
testIterator()639     public void testIterator() throws InterruptedException {
640         LinkedBlockingQueue q = populatedQueue(SIZE);
641         Iterator it = q.iterator();
642         int i;
643         for (i = 0; it.hasNext(); i++)
644             assertTrue(q.contains(it.next()));
645         assertEquals(i, SIZE);
646         assertIteratorExhausted(it);
647 
648         it = q.iterator();
649         for (i = 0; it.hasNext(); i++)
650             assertEquals(it.next(), q.take());
651         assertEquals(i, SIZE);
652         assertIteratorExhausted(it);
653     }
654 
655     /**
656      * iterator of empty collection has no elements
657      */
testEmptyIterator()658     public void testEmptyIterator() {
659         assertIteratorExhausted(new LinkedBlockingQueue().iterator());
660     }
661 
662     /**
663      * iterator.remove removes current element
664      */
testIteratorRemove()665     public void testIteratorRemove() {
666         final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
667         q.add(two);
668         q.add(one);
669         q.add(three);
670 
671         Iterator it = q.iterator();
672         it.next();
673         it.remove();
674 
675         it = q.iterator();
676         assertSame(it.next(), one);
677         assertSame(it.next(), three);
678         assertFalse(it.hasNext());
679     }
680 
681     /**
682      * iterator ordering is FIFO
683      */
testIteratorOrdering()684     public void testIteratorOrdering() {
685         final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
686         q.add(one);
687         q.add(two);
688         q.add(three);
689         assertEquals(0, q.remainingCapacity());
690         int k = 0;
691         for (Iterator it = q.iterator(); it.hasNext();) {
692             assertEquals(++k, it.next());
693         }
694         assertEquals(3, k);
695     }
696 
697     /**
698      * Modifications do not cause iterators to fail
699      */
testWeaklyConsistentIteration()700     public void testWeaklyConsistentIteration() {
701         final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
702         q.add(one);
703         q.add(two);
704         q.add(three);
705         for (Iterator it = q.iterator(); it.hasNext();) {
706             q.remove();
707             it.next();
708         }
709         assertEquals(0, q.size());
710     }
711 
712     /**
713      * toString contains toStrings of elements
714      */
testToString()715     public void testToString() {
716         LinkedBlockingQueue q = populatedQueue(SIZE);
717         String s = q.toString();
718         for (int i = 0; i < SIZE; ++i) {
719             assertTrue(s.contains(String.valueOf(i)));
720         }
721     }
722 
723     /**
724      * offer transfers elements across Executor tasks
725      */
testOfferInExecutor()726     public void testOfferInExecutor() {
727         final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
728         q.add(one);
729         q.add(two);
730         ExecutorService executor = Executors.newFixedThreadPool(2);
731         final CheckedBarrier threadsStarted = new CheckedBarrier(2);
732         executor.execute(new CheckedRunnable() {
733             public void realRun() throws InterruptedException {
734                 assertFalse(q.offer(three));
735                 threadsStarted.await();
736                 assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
737                 assertEquals(0, q.remainingCapacity());
738             }});
739 
740         executor.execute(new CheckedRunnable() {
741             public void realRun() throws InterruptedException {
742                 threadsStarted.await();
743                 assertSame(one, q.take());
744             }});
745 
746         joinPool(executor);
747     }
748 
749     /**
750      * timed poll retrieves elements across Executor threads
751      */
testPollInExecutor()752     public void testPollInExecutor() {
753         final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
754         final CheckedBarrier threadsStarted = new CheckedBarrier(2);
755         ExecutorService executor = Executors.newFixedThreadPool(2);
756         executor.execute(new CheckedRunnable() {
757             public void realRun() throws InterruptedException {
758                 assertNull(q.poll());
759                 threadsStarted.await();
760                 assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
761                 checkEmpty(q);
762             }});
763 
764         executor.execute(new CheckedRunnable() {
765             public void realRun() throws InterruptedException {
766                 threadsStarted.await();
767                 q.put(one);
768             }});
769 
770         joinPool(executor);
771     }
772 
773     /**
774      * A deserialized serialized queue has same elements in same order
775      */
testSerialization()776     public void testSerialization() throws Exception {
777         Queue x = populatedQueue(SIZE);
778         Queue y = serialClone(x);
779 
780         assertNotSame(x, y);
781         assertEquals(x.size(), y.size());
782         assertEquals(x.toString(), y.toString());
783         assertTrue(Arrays.equals(x.toArray(), y.toArray()));
784         while (!x.isEmpty()) {
785             assertFalse(y.isEmpty());
786             assertEquals(x.remove(), y.remove());
787         }
788         assertTrue(y.isEmpty());
789     }
790 
791     /**
792      * drainTo(c) empties queue into another collection c
793      */
testDrainTo()794     public void testDrainTo() {
795         LinkedBlockingQueue q = populatedQueue(SIZE);
796         ArrayList l = new ArrayList();
797         q.drainTo(l);
798         assertEquals(0, q.size());
799         assertEquals(SIZE, l.size());
800         for (int i = 0; i < SIZE; ++i)
801             assertEquals(l.get(i), new Integer(i));
802         q.add(zero);
803         q.add(one);
804         assertFalse(q.isEmpty());
805         assertTrue(q.contains(zero));
806         assertTrue(q.contains(one));
807         l.clear();
808         q.drainTo(l);
809         assertEquals(0, q.size());
810         assertEquals(2, l.size());
811         for (int i = 0; i < 2; ++i)
812             assertEquals(l.get(i), new Integer(i));
813     }
814 
815     /**
816      * drainTo empties full queue, unblocking a waiting put.
817      */
testDrainToWithActivePut()818     public void testDrainToWithActivePut() throws InterruptedException {
819         final LinkedBlockingQueue q = populatedQueue(SIZE);
820         Thread t = new Thread(new CheckedRunnable() {
821             public void realRun() throws InterruptedException {
822                 q.put(new Integer(SIZE+1));
823             }});
824 
825         t.start();
826         ArrayList l = new ArrayList();
827         q.drainTo(l);
828         assertTrue(l.size() >= SIZE);
829         for (int i = 0; i < SIZE; ++i)
830             assertEquals(l.get(i), new Integer(i));
831         t.join();
832         assertTrue(q.size() + l.size() >= SIZE);
833     }
834 
835     /**
836      * drainTo(c, n) empties first min(n, size) elements of queue into c
837      */
testDrainToN()838     public void testDrainToN() {
839         LinkedBlockingQueue q = new LinkedBlockingQueue();
840         for (int i = 0; i < SIZE + 2; ++i) {
841             for (int j = 0; j < SIZE; j++)
842                 assertTrue(q.offer(new Integer(j)));
843             ArrayList l = new ArrayList();
844             q.drainTo(l, i);
845             int k = (i < SIZE) ? i : SIZE;
846             assertEquals(k, l.size());
847             assertEquals(SIZE-k, q.size());
848             for (int j = 0; j < k; ++j)
849                 assertEquals(l.get(j), new Integer(j));
850             do {} while (q.poll() != null);
851         }
852     }
853 
854     /**
855      * remove(null), contains(null) always return false
856      */
testNeverContainsNull()857     public void testNeverContainsNull() {
858         Collection<?>[] qs = {
859             new LinkedBlockingQueue<Object>(),
860             populatedQueue(2),
861         };
862 
863         for (Collection<?> q : qs) {
864             assertFalse(q.contains(null));
865             assertFalse(q.remove(null));
866         }
867     }
868 
869 }
870