ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/LinkedBlockingQueueTest.java
(Generate patch)

Comparing jsr166/src/test/tck/LinkedBlockingQueueTest.java (file contents):
Revision 1.24 by jsr166, Tue Dec 1 06:03:49 2009 UTC vs.
Revision 1.64 by jsr166, Sun Oct 16 20:44:18 2016 UTC

# Line 1 | Line 1
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/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.*;
11 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.io.*;
10 >
11 > import java.util.ArrayList;
12 > import java.util.Arrays;
13 > import java.util.Collection;
14 > import java.util.Iterator;
15 > import java.util.NoSuchElementException;
16 > import java.util.Queue;
17 > import java.util.concurrent.BlockingQueue;
18 > import java.util.concurrent.CountDownLatch;
19 > import java.util.concurrent.Executors;
20 > import java.util.concurrent.ExecutorService;
21 > import java.util.concurrent.LinkedBlockingQueue;
22 >
23 > import junit.framework.Test;
24  
25   public class LinkedBlockingQueueTest extends JSR166TestCase {
26  
27 +    public static class Unbounded extends BlockingQueueTest {
28 +        protected BlockingQueue emptyCollection() {
29 +            return new LinkedBlockingQueue();
30 +        }
31 +    }
32 +
33 +    public static class Bounded extends BlockingQueueTest {
34 +        protected BlockingQueue emptyCollection() {
35 +            return new LinkedBlockingQueue(SIZE);
36 +        }
37 +    }
38 +
39      public static void main(String[] args) {
40 <        junit.textui.TestRunner.run (suite());
40 >        main(suite(), args);
41      }
42  
43      public static Test suite() {
44 <        return new TestSuite(LinkedBlockingQueueTest.class);
44 >        return newTestSuite(LinkedBlockingQueueTest.class,
45 >                            new Unbounded().testSuite(),
46 >                            new Bounded().testSuite());
47      }
48  
25
49      /**
50 <     * Create a queue of given size containing consecutive
51 <     * Integers 0 ... n.
50 >     * Returns a new queue of given size containing consecutive
51 >     * Integers 0 ... n - 1.
52       */
53 <    private LinkedBlockingQueue populatedQueue(int n) {
54 <        LinkedBlockingQueue q = new LinkedBlockingQueue(n);
53 >    private LinkedBlockingQueue<Integer> populatedQueue(int n) {
54 >        LinkedBlockingQueue<Integer> q =
55 >            new LinkedBlockingQueue<Integer>(n);
56          assertTrue(q.isEmpty());
57          for (int i = 0; i < n; i++)
58              assertTrue(q.offer(new Integer(i)));
59          assertFalse(q.isEmpty());
60          assertEquals(0, q.remainingCapacity());
61          assertEquals(n, q.size());
62 +        assertEquals((Integer) 0, q.peek());
63          return q;
64      }
65  
# Line 48 | Line 73 | public class LinkedBlockingQueueTest ext
73      }
74  
75      /**
76 <     * Constructor throws IAE if capacity argument nonpositive
76 >     * Constructor throws IllegalArgumentException if capacity argument nonpositive
77       */
78      public void testConstructor2() {
79          try {
80 <            LinkedBlockingQueue q = new LinkedBlockingQueue(0);
80 >            new LinkedBlockingQueue(0);
81              shouldThrow();
82          } catch (IllegalArgumentException success) {}
83      }
84  
85      /**
86 <     * Initializing from null Collection throws NPE
86 >     * Initializing from null Collection throws NullPointerException
87       */
88      public void testConstructor3() {
89          try {
90 <            LinkedBlockingQueue q = new LinkedBlockingQueue(null);
90 >            new LinkedBlockingQueue(null);
91              shouldThrow();
92          } catch (NullPointerException success) {}
93      }
94  
95      /**
96 <     * Initializing from Collection of null elements throws NPE
96 >     * Initializing from Collection of null elements throws NullPointerException
97       */
98      public void testConstructor4() {
99 +        Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
100          try {
101 <            Integer[] ints = new Integer[SIZE];
76 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
101 >            new LinkedBlockingQueue(elements);
102              shouldThrow();
103          } catch (NullPointerException success) {}
104      }
105  
106      /**
107 <     * Initializing from Collection with some null elements throws NPE
107 >     * Initializing from Collection with some null elements throws
108 >     * NullPointerException
109       */
110      public void testConstructor5() {
111 +        Integer[] ints = new Integer[SIZE];
112 +        for (int i = 0; i < SIZE - 1; ++i)
113 +            ints[i] = new Integer(i);
114 +        Collection<Integer> elements = Arrays.asList(ints);
115          try {
116 <            Integer[] ints = new Integer[SIZE];
87 <            for (int i = 0; i < SIZE-1; ++i)
88 <                ints[i] = new Integer(i);
89 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
116 >            new LinkedBlockingQueue(elements);
117              shouldThrow();
118          } catch (NullPointerException success) {}
119      }
# Line 122 | Line 149 | public class LinkedBlockingQueueTest ext
149       * remainingCapacity decreases on add, increases on remove
150       */
151      public void testRemainingCapacity() {
152 <        LinkedBlockingQueue q = populatedQueue(SIZE);
152 >        BlockingQueue q = populatedQueue(SIZE);
153          for (int i = 0; i < SIZE; ++i) {
154              assertEquals(i, q.remainingCapacity());
155 <            assertEquals(SIZE-i, q.size());
156 <            q.remove();
155 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
156 >            assertEquals(i, q.remove());
157          }
158          for (int i = 0; i < SIZE; ++i) {
159 <            assertEquals(SIZE-i, q.remainingCapacity());
160 <            assertEquals(i, q.size());
161 <            q.add(new Integer(i));
159 >            assertEquals(SIZE - i, q.remainingCapacity());
160 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
161 >            assertTrue(q.add(i));
162          }
163      }
164  
165      /**
139     * offer(null) throws NPE
140     */
141    public void testOfferNull() {
142        try {
143            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
144            q.offer(null);
145            shouldThrow();
146        } catch (NullPointerException success) {}
147    }
148
149    /**
150     * add(null) throws NPE
151     */
152    public void testAddNull() {
153        try {
154            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
155            q.add(null);
156            shouldThrow();
157        } catch (NullPointerException success) {}
158    }
159
160    /**
166       * Offer succeeds if not full; fails if full
167       */
168      public void testOffer() {
# Line 167 | Line 172 | public class LinkedBlockingQueueTest ext
172      }
173  
174      /**
175 <     * add succeeds if not full; throws ISE if full
175 >     * add succeeds if not full; throws IllegalStateException if full
176       */
177      public void testAdd() {
178 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
179 +        for (int i = 0; i < SIZE; ++i)
180 +            assertTrue(q.add(new Integer(i)));
181 +        assertEquals(0, q.remainingCapacity());
182          try {
174            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
175            for (int i = 0; i < SIZE; ++i) {
176                assertTrue(q.add(new Integer(i)));
177            }
178            assertEquals(0, q.remainingCapacity());
183              q.add(new Integer(SIZE));
184              shouldThrow();
185          } catch (IllegalStateException success) {}
186      }
187  
188      /**
189 <     * addAll(null) throws NPE
186 <     */
187 <    public void testAddAll1() {
188 <        try {
189 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
190 <            q.addAll(null);
191 <            shouldThrow();
192 <        } catch (NullPointerException success) {}
193 <    }
194 <
195 <    /**
196 <     * addAll(this) throws IAE
189 >     * addAll(this) throws IllegalArgumentException
190       */
191      public void testAddAllSelf() {
192 +        LinkedBlockingQueue q = populatedQueue(SIZE);
193          try {
200            LinkedBlockingQueue q = populatedQueue(SIZE);
194              q.addAll(q);
195              shouldThrow();
196          } catch (IllegalArgumentException success) {}
197      }
198  
199      /**
207     * addAll of a collection with null elements throws NPE
208     */
209    public void testAddAll2() {
210        try {
211            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
212            Integer[] ints = new Integer[SIZE];
213            q.addAll(Arrays.asList(ints));
214            shouldThrow();
215        } catch (NullPointerException success) {}
216    }
217    /**
200       * addAll of a collection with any null elements throws NPE after
201       * possibly adding some elements
202       */
203      public void testAddAll3() {
204 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
205 +        Integer[] ints = new Integer[SIZE];
206 +        for (int i = 0; i < SIZE - 1; ++i)
207 +            ints[i] = new Integer(i);
208 +        Collection<Integer> elements = Arrays.asList(ints);
209          try {
210 <            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
224 <            Integer[] ints = new Integer[SIZE];
225 <            for (int i = 0; i < SIZE-1; ++i)
226 <                ints[i] = new Integer(i);
227 <            q.addAll(Arrays.asList(ints));
210 >            q.addAll(elements);
211              shouldThrow();
212          } catch (NullPointerException success) {}
213      }
214 +
215      /**
216 <     * addAll throws ISE if not enough room
216 >     * addAll throws IllegalStateException if not enough room
217       */
218      public void testAddAll4() {
219 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE - 1);
220 +        Integer[] ints = new Integer[SIZE];
221 +        for (int i = 0; i < SIZE; ++i)
222 +            ints[i] = new Integer(i);
223 +        Collection<Integer> elements = Arrays.asList(ints);
224          try {
225 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
237 <            Integer[] ints = new Integer[SIZE];
238 <            for (int i = 0; i < SIZE; ++i)
239 <                ints[i] = new Integer(i);
240 <            q.addAll(Arrays.asList(ints));
225 >            q.addAll(elements);
226              shouldThrow();
227          } catch (IllegalStateException success) {}
228      }
229 +
230      /**
231       * Queue contains all elements, in traversal order, of successful addAll
232       */
# Line 257 | Line 243 | public class LinkedBlockingQueueTest ext
243      }
244  
245      /**
260     * put(null) throws NPE
261     */
262     public void testPutNull() throws InterruptedException {
263        try {
264            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
265            q.put(null);
266            shouldThrow();
267        } catch (NullPointerException success) {}
268     }
269
270    /**
246       * all elements successfully put are contained
247       */
248      public void testPut() throws InterruptedException {
249          LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
250          for (int i = 0; i < SIZE; ++i) {
251 <            Integer I = new Integer(i);
252 <            q.put(I);
253 <            assertTrue(q.contains(I));
251 >            Integer x = new Integer(i);
252 >            q.put(x);
253 >            assertTrue(q.contains(x));
254          }
255          assertEquals(0, q.remainingCapacity());
256      }
# Line 285 | Line 260 | public class LinkedBlockingQueueTest ext
260       */
261      public void testBlockingPut() throws InterruptedException {
262          final LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
263 <        Thread t = new Thread(new CheckedRunnable() {
263 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
264 >        Thread t = newStartedThread(new CheckedRunnable() {
265              public void realRun() throws InterruptedException {
266                  for (int i = 0; i < SIZE; ++i)
267                      q.put(i);
268                  assertEquals(SIZE, q.size());
269                  assertEquals(0, q.remainingCapacity());
270 +
271 +                Thread.currentThread().interrupt();
272 +                try {
273 +                    q.put(99);
274 +                    shouldThrow();
275 +                } catch (InterruptedException success) {}
276 +                assertFalse(Thread.interrupted());
277 +
278 +                pleaseInterrupt.countDown();
279                  try {
280                      q.put(99);
281                      shouldThrow();
282                  } catch (InterruptedException success) {}
283 +                assertFalse(Thread.interrupted());
284              }});
285  
286 <        t.start();
287 <        Thread.sleep(SHORT_DELAY_MS);
286 >        await(pleaseInterrupt);
287 >        assertThreadStaysAlive(t);
288          t.interrupt();
289 <        t.join();
289 >        awaitTermination(t);
290          assertEquals(SIZE, q.size());
291          assertEquals(0, q.remainingCapacity());
292      }
293  
294      /**
295 <     * put blocks waiting for take when full
295 >     * put blocks interruptibly waiting for take when full
296       */
297      public void testPutWithTake() throws InterruptedException {
298          final int capacity = 2;
299          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
300 <        Thread t = new Thread(new CheckedRunnable() {
300 >        final CountDownLatch pleaseTake = new CountDownLatch(1);
301 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
302 >        Thread t = newStartedThread(new CheckedRunnable() {
303              public void realRun() throws InterruptedException {
304 <                for (int i = 0; i < capacity + 1; i++)
304 >                for (int i = 0; i < capacity; i++)
305                      q.put(i);
306 +                pleaseTake.countDown();
307 +                q.put(86);
308 +
309 +                pleaseInterrupt.countDown();
310                  try {
311                      q.put(99);
312                      shouldThrow();
313                  } catch (InterruptedException success) {}
314 +                assertFalse(Thread.interrupted());
315              }});
316  
317 <        t.start();
318 <        Thread.sleep(SHORT_DELAY_MS);
326 <        assertEquals(q.remainingCapacity(), 0);
317 >        await(pleaseTake);
318 >        assertEquals(0, q.remainingCapacity());
319          assertEquals(0, q.take());
320 <        Thread.sleep(SHORT_DELAY_MS);
320 >
321 >        await(pleaseInterrupt);
322 >        assertThreadStaysAlive(t);
323          t.interrupt();
324 <        t.join();
325 <        assertEquals(q.remainingCapacity(), 0);
324 >        awaitTermination(t);
325 >        assertEquals(0, q.remainingCapacity());
326      }
327  
328      /**
329       * timed offer times out if full and elements not taken
330       */
331 <    public void testTimedOffer() throws InterruptedException {
331 >    public void testTimedOffer() {
332          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
333 <        Thread t = new Thread(new CheckedRunnable() {
333 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
334 >        Thread t = newStartedThread(new CheckedRunnable() {
335              public void realRun() throws InterruptedException {
336                  q.put(new Object());
337                  q.put(new Object());
338 <                assertFalse(q.offer(new Object(), SHORT_DELAY_MS, MILLISECONDS));
338 >                long startTime = System.nanoTime();
339 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
340 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
341 >                pleaseInterrupt.countDown();
342                  try {
343 <                    q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
343 >                    q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
344                      shouldThrow();
345                  } catch (InterruptedException success) {}
346              }});
347  
348 <        t.start();
349 <        Thread.sleep(SMALL_DELAY_MS);
348 >        await(pleaseInterrupt);
349 >        assertThreadStaysAlive(t);
350          t.interrupt();
351 <        t.join();
351 >        awaitTermination(t);
352      }
353  
354      /**
# Line 364 | Line 362 | public class LinkedBlockingQueueTest ext
362      }
363  
364      /**
367     * take blocks interruptibly when empty
368     */
369    public void testTakeFromEmpty() throws InterruptedException {
370        final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
371        Thread t = new ThreadShouldThrow(InterruptedException.class) {
372            public void realRun() throws InterruptedException {
373                q.take();
374            }};
375
376        t.start();
377        Thread.sleep(SHORT_DELAY_MS);
378        t.interrupt();
379        t.join();
380    }
381
382    /**
365       * Take removes existing elements until empty, then blocks interruptibly
366       */
367      public void testBlockingTake() throws InterruptedException {
368 <        final LinkedBlockingQueue q = populatedQueue(SIZE);
369 <        Thread t = new Thread(new CheckedRunnable() {
368 >        final BlockingQueue q = populatedQueue(SIZE);
369 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
370 >        Thread t = newStartedThread(new CheckedRunnable() {
371              public void realRun() throws InterruptedException {
372                  for (int i = 0; i < SIZE; ++i) {
373                      assertEquals(i, q.take());
374                  }
375 +
376 +                Thread.currentThread().interrupt();
377 +                try {
378 +                    q.take();
379 +                    shouldThrow();
380 +                } catch (InterruptedException success) {}
381 +                assertFalse(Thread.interrupted());
382 +
383 +                pleaseInterrupt.countDown();
384                  try {
385                      q.take();
386                      shouldThrow();
387                  } catch (InterruptedException success) {}
388 +                assertFalse(Thread.interrupted());
389              }});
390  
391 <        t.start();
392 <        Thread.sleep(SHORT_DELAY_MS);
391 >        await(pleaseInterrupt);
392 >        assertThreadStaysAlive(t);
393          t.interrupt();
394 <        t.join();
394 >        awaitTermination(t);
395      }
396  
397      /**
# Line 413 | Line 406 | public class LinkedBlockingQueueTest ext
406      }
407  
408      /**
409 <     * timed pool with zero timeout succeeds when non-empty, else times out
409 >     * timed poll with zero timeout succeeds when non-empty, else times out
410       */
411      public void testTimedPoll0() throws InterruptedException {
412          LinkedBlockingQueue q = populatedQueue(SIZE);
# Line 424 | Line 417 | public class LinkedBlockingQueueTest ext
417      }
418  
419      /**
420 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
420 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
421       */
422      public void testTimedPoll() throws InterruptedException {
423 <        LinkedBlockingQueue q = populatedQueue(SIZE);
423 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
424          for (int i = 0; i < SIZE; ++i) {
425 <            assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
426 <        }
427 <        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
425 >            long startTime = System.nanoTime();
426 >            assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
427 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
428 >        }
429 >        long startTime = System.nanoTime();
430 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
431 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
432 >        checkEmpty(q);
433      }
434  
435      /**
# Line 439 | Line 437 | public class LinkedBlockingQueueTest ext
437       * returning timeout status
438       */
439      public void testInterruptedTimedPoll() throws InterruptedException {
440 <        Thread t = new Thread(new CheckedRunnable() {
440 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
441 >        final CountDownLatch aboutToWait = new CountDownLatch(1);
442 >        Thread t = newStartedThread(new CheckedRunnable() {
443              public void realRun() throws InterruptedException {
444 <                LinkedBlockingQueue q = populatedQueue(SIZE);
444 >                long startTime = System.nanoTime();
445                  for (int i = 0; i < SIZE; ++i) {
446 <                    assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
446 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
447                  }
448 <                try {
449 <                    q.poll(SMALL_DELAY_MS, MILLISECONDS);
450 <                    shouldThrow();
451 <                } catch (InterruptedException success) {}
452 <            }});
453 <
454 <        t.start();
455 <        Thread.sleep(SHORT_DELAY_MS);
456 <        t.interrupt();
457 <        t.join();
458 <    }
459 <
460 <    /**
461 <     *  timed poll before a delayed offer fails; after offer succeeds;
462 <     *  on interruption throws
463 <     */
464 <    public void testTimedPollWithOffer() throws InterruptedException {
465 <        final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
466 <        Thread t = new Thread(new CheckedRunnable() {
467 <            public void realRun() throws InterruptedException {
468 <                assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
469 <                assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
448 >                aboutToWait.countDown();
449                  try {
450                      q.poll(LONG_DELAY_MS, MILLISECONDS);
451                      shouldThrow();
452 <                } catch (InterruptedException success) {}
452 >                } catch (InterruptedException success) {
453 >                    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
454 >                }
455              }});
456  
457 <        t.start();
458 <        Thread.sleep(SMALL_DELAY_MS);
478 <        assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
457 >        await(aboutToWait);
458 >        waitForThreadToEnterWaitState(t);
459          t.interrupt();
460 <        t.join();
460 >        awaitTermination(t);
461 >        checkEmpty(q);
462      }
463  
464      /**
# Line 524 | Line 505 | public class LinkedBlockingQueueTest ext
505      }
506  
507      /**
527     * remove(x) removes x and returns true if present
528     */
529    public void testRemoveElement() {
530        LinkedBlockingQueue q = populatedQueue(SIZE);
531        for (int i = 1; i < SIZE; i+=2) {
532            assertTrue(q.remove(new Integer(i)));
533        }
534        for (int i = 0; i < SIZE; i+=2) {
535            assertTrue(q.remove(new Integer(i)));
536            assertFalse(q.remove(new Integer(i+1)));
537        }
538        assertTrue(q.isEmpty());
539    }
540
541    /**
508       * An add following remove(x) succeeds
509       */
510      public void testRemoveElementAndAdd() throws InterruptedException {
# Line 548 | Line 514 | public class LinkedBlockingQueueTest ext
514          assertTrue(q.remove(new Integer(1)));
515          assertTrue(q.remove(new Integer(2)));
516          assertTrue(q.add(new Integer(3)));
517 <        assertTrue(q.take() != null);
517 >        assertNotNull(q.take());
518      }
519  
520      /**
# Line 607 | Line 573 | public class LinkedBlockingQueueTest ext
573                  assertTrue(changed);
574  
575              assertTrue(q.containsAll(p));
576 <            assertEquals(SIZE-i, q.size());
576 >            assertEquals(SIZE - i, q.size());
577              p.remove();
578          }
579      }
# Line 620 | Line 586 | public class LinkedBlockingQueueTest ext
586              LinkedBlockingQueue q = populatedQueue(SIZE);
587              LinkedBlockingQueue p = populatedQueue(i);
588              assertTrue(q.removeAll(p));
589 <            assertEquals(SIZE-i, q.size());
589 >            assertEquals(SIZE - i, q.size());
590              for (int j = 0; j < i; ++j) {
591 <                Integer I = (Integer)(p.remove());
592 <                assertFalse(q.contains(I));
591 >                Integer x = (Integer)(p.remove());
592 >                assertFalse(q.contains(x));
593              }
594          }
595      }
596  
597      /**
598 <     * toArray contains all elements
598 >     * toArray contains all elements in FIFO order
599       */
600 <    public void testToArray() throws InterruptedException {
600 >    public void testToArray() {
601          LinkedBlockingQueue q = populatedQueue(SIZE);
602          Object[] o = q.toArray();
603          for (int i = 0; i < o.length; i++)
604 <            assertEquals(o[i], q.take());
604 >            assertSame(o[i], q.poll());
605      }
606  
607      /**
608 <     * toArray(a) contains all elements
608 >     * toArray(a) contains all elements in FIFO order
609       */
610      public void testToArray2() throws InterruptedException {
611 <        LinkedBlockingQueue q = populatedQueue(SIZE);
611 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
612          Integer[] ints = new Integer[SIZE];
613 <        ints = (Integer[])q.toArray(ints);
613 >        Integer[] array = q.toArray(ints);
614 >        assertSame(ints, array);
615          for (int i = 0; i < ints.length; i++)
616 <            assertEquals(ints[i], q.take());
616 >            assertSame(ints[i], q.poll());
617      }
618  
619      /**
620 <     * toArray(null) throws NPE
654 <     */
655 <    public void testToArray_BadArg() {
656 <        LinkedBlockingQueue q = populatedQueue(SIZE);
657 <        try {
658 <            Object o[] = q.toArray(null);
659 <            shouldThrow();
660 <        } catch (NullPointerException success) {}
661 <    }
662 <
663 <    /**
664 <     * toArray with incompatible array type throws CCE
620 >     * toArray(incompatible array type) throws ArrayStoreException
621       */
622      public void testToArray1_BadArg() {
623          LinkedBlockingQueue q = populatedQueue(SIZE);
624          try {
625 <            Object o[] = q.toArray(new String[10]);
625 >            q.toArray(new String[10]);
626              shouldThrow();
627          } catch (ArrayStoreException success) {}
628      }
629  
674
630      /**
631       * iterator iterates through all elements
632       */
633      public void testIterator() throws InterruptedException {
634          LinkedBlockingQueue q = populatedQueue(SIZE);
635          Iterator it = q.iterator();
636 <        while (it.hasNext()) {
636 >        int i;
637 >        for (i = 0; it.hasNext(); i++)
638 >            assertTrue(q.contains(it.next()));
639 >        assertEquals(i, SIZE);
640 >        assertIteratorExhausted(it);
641 >
642 >        it = q.iterator();
643 >        for (i = 0; it.hasNext(); i++)
644              assertEquals(it.next(), q.take());
645 <        }
645 >        assertEquals(i, SIZE);
646 >        assertIteratorExhausted(it);
647 >    }
648 >
649 >    /**
650 >     * iterator of empty collection has no elements
651 >     */
652 >    public void testEmptyIterator() {
653 >        assertIteratorExhausted(new LinkedBlockingQueue().iterator());
654      }
655  
656      /**
657       * iterator.remove removes current element
658       */
659 <    public void testIteratorRemove () {
659 >    public void testIteratorRemove() {
660          final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
661          q.add(two);
662          q.add(one);
# Line 697 | Line 667 | public class LinkedBlockingQueueTest ext
667          it.remove();
668  
669          it = q.iterator();
670 <        assertEquals(it.next(), one);
671 <        assertEquals(it.next(), three);
670 >        assertSame(it.next(), one);
671 >        assertSame(it.next(), three);
672          assertFalse(it.hasNext());
673      }
674  
705
675      /**
676       * iterator ordering is FIFO
677       */
# Line 722 | Line 691 | public class LinkedBlockingQueueTest ext
691      /**
692       * Modifications do not cause iterators to fail
693       */
694 <    public void testWeaklyConsistentIteration () {
694 >    public void testWeaklyConsistentIteration() {
695          final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
696          q.add(one);
697          q.add(two);
# Line 734 | Line 703 | public class LinkedBlockingQueueTest ext
703          assertEquals(0, q.size());
704      }
705  
737
706      /**
707       * toString contains toStrings of elements
708       */
# Line 742 | Line 710 | public class LinkedBlockingQueueTest ext
710          LinkedBlockingQueue q = populatedQueue(SIZE);
711          String s = q.toString();
712          for (int i = 0; i < SIZE; ++i) {
713 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
713 >            assertTrue(s.contains(String.valueOf(i)));
714          }
715      }
716  
749
717      /**
718       * offer transfers elements across Executor tasks
719       */
# Line 754 | Line 721 | public class LinkedBlockingQueueTest ext
721          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
722          q.add(one);
723          q.add(two);
724 <        ExecutorService executor = Executors.newFixedThreadPool(2);
725 <        executor.execute(new CheckedRunnable() {
726 <            public void realRun() throws InterruptedException {
727 <                assertFalse(q.offer(three));
728 <                assertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
729 <                assertEquals(0, q.remainingCapacity());
730 <            }});
731 <
732 <        executor.execute(new CheckedRunnable() {
733 <            public void realRun() throws InterruptedException {
734 <                Thread.sleep(SMALL_DELAY_MS);
735 <                assertSame(one, q.take());
736 <            }});
737 <
738 <        joinPool(executor);
724 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
725 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
726 >        try (PoolCleaner cleaner = cleaner(executor)) {
727 >            executor.execute(new CheckedRunnable() {
728 >                public void realRun() throws InterruptedException {
729 >                    assertFalse(q.offer(three));
730 >                    threadsStarted.await();
731 >                    assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
732 >                    assertEquals(0, q.remainingCapacity());
733 >                }});
734 >
735 >            executor.execute(new CheckedRunnable() {
736 >                public void realRun() throws InterruptedException {
737 >                    threadsStarted.await();
738 >                    assertSame(one, q.take());
739 >                }});
740 >        }
741      }
742  
743      /**
744 <     * poll retrieves elements across Executor threads
744 >     * timed poll retrieves elements across Executor threads
745       */
746      public void testPollInExecutor() {
747          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
748 <        ExecutorService executor = Executors.newFixedThreadPool(2);
749 <        executor.execute(new CheckedRunnable() {
750 <            public void realRun() throws InterruptedException {
751 <                assertNull(q.poll());
752 <                assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
753 <                assertTrue(q.isEmpty());
754 <            }});
755 <
756 <        executor.execute(new CheckedRunnable() {
757 <            public void realRun() throws InterruptedException {
758 <                Thread.sleep(SMALL_DELAY_MS);
759 <                q.put(one);
760 <            }});
761 <
762 <        joinPool(executor);
748 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
749 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
750 >        try (PoolCleaner cleaner = cleaner(executor)) {
751 >            executor.execute(new CheckedRunnable() {
752 >                public void realRun() throws InterruptedException {
753 >                    assertNull(q.poll());
754 >                    threadsStarted.await();
755 >                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
756 >                    checkEmpty(q);
757 >                }});
758 >
759 >            executor.execute(new CheckedRunnable() {
760 >                public void realRun() throws InterruptedException {
761 >                    threadsStarted.await();
762 >                    q.put(one);
763 >                }});
764 >        }
765      }
766  
767      /**
768       * A deserialized serialized queue has same elements in same order
769       */
770      public void testSerialization() throws Exception {
771 <        LinkedBlockingQueue q = populatedQueue(SIZE);
772 <
802 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
803 <        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
804 <        out.writeObject(q);
805 <        out.close();
806 <
807 <        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
808 <        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
809 <        LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
810 <        assertEquals(q.size(), r.size());
811 <        while (!q.isEmpty())
812 <            assertEquals(q.remove(), r.remove());
813 <    }
771 >        Queue x = populatedQueue(SIZE);
772 >        Queue y = serialClone(x);
773  
774 <    /**
775 <     * drainTo(null) throws NPE
776 <     */
777 <    public void testDrainToNull() {
778 <        LinkedBlockingQueue q = populatedQueue(SIZE);
779 <        try {
780 <            q.drainTo(null);
781 <            shouldThrow();
782 <        } catch (NullPointerException success) {}
824 <    }
825 <
826 <    /**
827 <     * drainTo(this) throws IAE
828 <     */
829 <    public void testDrainToSelf() {
830 <        LinkedBlockingQueue q = populatedQueue(SIZE);
831 <        try {
832 <            q.drainTo(q);
833 <            shouldThrow();
834 <        } catch (IllegalArgumentException success) {}
774 >        assertNotSame(x, y);
775 >        assertEquals(x.size(), y.size());
776 >        assertEquals(x.toString(), y.toString());
777 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
778 >        while (!x.isEmpty()) {
779 >            assertFalse(y.isEmpty());
780 >            assertEquals(x.remove(), y.remove());
781 >        }
782 >        assertTrue(y.isEmpty());
783      }
784  
785      /**
# Line 841 | Line 789 | public class LinkedBlockingQueueTest ext
789          LinkedBlockingQueue q = populatedQueue(SIZE);
790          ArrayList l = new ArrayList();
791          q.drainTo(l);
792 <        assertEquals(q.size(), 0);
793 <        assertEquals(l.size(), SIZE);
792 >        assertEquals(0, q.size());
793 >        assertEquals(SIZE, l.size());
794          for (int i = 0; i < SIZE; ++i)
795              assertEquals(l.get(i), new Integer(i));
796          q.add(zero);
# Line 852 | Line 800 | public class LinkedBlockingQueueTest ext
800          assertTrue(q.contains(one));
801          l.clear();
802          q.drainTo(l);
803 <        assertEquals(q.size(), 0);
804 <        assertEquals(l.size(), 2);
803 >        assertEquals(0, q.size());
804 >        assertEquals(2, l.size());
805          for (int i = 0; i < 2; ++i)
806              assertEquals(l.get(i), new Integer(i));
807      }
# Line 865 | Line 813 | public class LinkedBlockingQueueTest ext
813          final LinkedBlockingQueue q = populatedQueue(SIZE);
814          Thread t = new Thread(new CheckedRunnable() {
815              public void realRun() throws InterruptedException {
816 <                q.put(new Integer(SIZE+1));
816 >                q.put(new Integer(SIZE + 1));
817              }});
818  
819          t.start();
# Line 879 | Line 827 | public class LinkedBlockingQueueTest ext
827      }
828  
829      /**
830 <     * drainTo(null, n) throws NPE
883 <     */
884 <    public void testDrainToNullN() {
885 <        LinkedBlockingQueue q = populatedQueue(SIZE);
886 <        try {
887 <            q.drainTo(null, 0);
888 <            shouldThrow();
889 <        } catch (NullPointerException success) {}
890 <    }
891 <
892 <    /**
893 <     * drainTo(this, n) throws IAE
894 <     */
895 <    public void testDrainToSelfN() {
896 <        LinkedBlockingQueue q = populatedQueue(SIZE);
897 <        try {
898 <            q.drainTo(q, 0);
899 <            shouldThrow();
900 <        } catch (IllegalArgumentException success) {}
901 <    }
902 <
903 <    /**
904 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
830 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
831       */
832      public void testDrainToN() {
833          LinkedBlockingQueue q = new LinkedBlockingQueue();
# Line 910 | Line 836 | public class LinkedBlockingQueueTest ext
836                  assertTrue(q.offer(new Integer(j)));
837              ArrayList l = new ArrayList();
838              q.drainTo(l, i);
839 <            int k = (i < SIZE)? i : SIZE;
840 <            assertEquals(l.size(), k);
841 <            assertEquals(q.size(), SIZE-k);
839 >            int k = (i < SIZE) ? i : SIZE;
840 >            assertEquals(k, l.size());
841 >            assertEquals(SIZE - k, q.size());
842              for (int j = 0; j < k; ++j)
843                  assertEquals(l.get(j), new Integer(j));
844 <            while (q.poll() != null) ;
844 >            do {} while (q.poll() != null);
845 >        }
846 >    }
847 >
848 >    /**
849 >     * remove(null), contains(null) always return false
850 >     */
851 >    public void testNeverContainsNull() {
852 >        Collection<?>[] qs = {
853 >            new LinkedBlockingQueue<Object>(),
854 >            populatedQueue(2),
855 >        };
856 >
857 >        for (Collection<?> q : qs) {
858 >            assertFalse(q.contains(null));
859 >            assertFalse(q.remove(null));
860          }
861      }
862  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines