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.38 by jsr166, Thu Nov 18 20:21:53 2010 UTC vs.
Revision 1.80 by jsr166, Thu Sep 5 20:54:24 2019 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  
# Line 22 | Line 32 | public class LinkedBlockingQueueTest ext
32  
33      public static class Bounded extends BlockingQueueTest {
34          protected BlockingQueue emptyCollection() {
35 <            return new LinkedBlockingQueue(20);
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 +        class Implementation implements CollectionImplementation {
45 +            public Class<?> klazz() { return LinkedBlockingQueue.class; }
46 +            public Collection emptyCollection() { return new LinkedBlockingQueue(); }
47 +            public Object makeElement(int i) { return i; }
48 +            public boolean isConcurrent() { return true; }
49 +            public boolean permitsNulls() { return false; }
50 +        }
51          return newTestSuite(LinkedBlockingQueueTest.class,
52                              new Unbounded().testSuite(),
53 <                            new Bounded().testSuite());
53 >                            new Bounded().testSuite(),
54 >                            CollectionTest.testSuite(new Implementation()));
55      }
56  
39
57      /**
58 <     * Create a queue of given size containing consecutive
59 <     * Integers 0 ... n.
58 >     * Returns a new queue of given size containing consecutive
59 >     * Integers 0 ... n - 1.
60       */
61 <    private LinkedBlockingQueue<Integer> populatedQueue(int n) {
62 <        LinkedBlockingQueue<Integer> q =
46 <            new LinkedBlockingQueue<Integer>(n);
61 >    private static LinkedBlockingQueue<Integer> populatedQueue(int n) {
62 >        LinkedBlockingQueue<Integer> q = new LinkedBlockingQueue<>(n);
63          assertTrue(q.isEmpty());
64          for (int i = 0; i < n; i++)
65              assertTrue(q.offer(new Integer(i)));
66          assertFalse(q.isEmpty());
67          assertEquals(0, q.remainingCapacity());
68          assertEquals(n, q.size());
69 +        assertEquals((Integer) 0, q.peek());
70          return q;
71      }
72  
# Line 63 | Line 80 | public class LinkedBlockingQueueTest ext
80      }
81  
82      /**
83 <     * Constructor throws IAE if capacity argument nonpositive
83 >     * Constructor throws IllegalArgumentException if capacity argument nonpositive
84       */
85      public void testConstructor2() {
86          try {
87 <            LinkedBlockingQueue q = new LinkedBlockingQueue(0);
87 >            new LinkedBlockingQueue(0);
88              shouldThrow();
89          } catch (IllegalArgumentException success) {}
90      }
91  
92      /**
93 <     * Initializing from null Collection throws NPE
93 >     * Initializing from null Collection throws NullPointerException
94       */
95      public void testConstructor3() {
96          try {
97 <            LinkedBlockingQueue q = new LinkedBlockingQueue(null);
97 >            new LinkedBlockingQueue(null);
98              shouldThrow();
99          } catch (NullPointerException success) {}
100      }
101  
102      /**
103 <     * Initializing from Collection of null elements throws NPE
103 >     * Initializing from Collection of null elements throws NullPointerException
104       */
105      public void testConstructor4() {
106 +        Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
107          try {
108 <            Integer[] ints = new Integer[SIZE];
91 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
108 >            new LinkedBlockingQueue(elements);
109              shouldThrow();
110          } catch (NullPointerException success) {}
111      }
112  
113      /**
114 <     * Initializing from Collection with some null elements throws NPE
114 >     * Initializing from Collection with some null elements throws
115 >     * NullPointerException
116       */
117      public void testConstructor5() {
118 +        Integer[] ints = new Integer[SIZE];
119 +        for (int i = 0; i < SIZE - 1; ++i)
120 +            ints[i] = new Integer(i);
121 +        Collection<Integer> elements = Arrays.asList(ints);
122          try {
123 <            Integer[] ints = new Integer[SIZE];
102 <            for (int i = 0; i < SIZE-1; ++i)
103 <                ints[i] = new Integer(i);
104 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
123 >            new LinkedBlockingQueue(elements);
124              shouldThrow();
125          } catch (NullPointerException success) {}
126      }
# Line 137 | Line 156 | public class LinkedBlockingQueueTest ext
156       * remainingCapacity decreases on add, increases on remove
157       */
158      public void testRemainingCapacity() {
159 <        LinkedBlockingQueue q = populatedQueue(SIZE);
159 >        BlockingQueue q = populatedQueue(SIZE);
160          for (int i = 0; i < SIZE; ++i) {
161              assertEquals(i, q.remainingCapacity());
162 <            assertEquals(SIZE-i, q.size());
163 <            q.remove();
162 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
163 >            assertEquals(i, q.remove());
164          }
165          for (int i = 0; i < SIZE; ++i) {
166 <            assertEquals(SIZE-i, q.remainingCapacity());
167 <            assertEquals(i, q.size());
168 <            q.add(new Integer(i));
166 >            assertEquals(SIZE - i, q.remainingCapacity());
167 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
168 >            assertTrue(q.add(i));
169          }
170      }
171  
172      /**
154     * offer(null) throws NPE
155     */
156    public void testOfferNull() {
157        try {
158            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
159            q.offer(null);
160            shouldThrow();
161        } catch (NullPointerException success) {}
162    }
163
164    /**
165     * add(null) throws NPE
166     */
167    public void testAddNull() {
168        try {
169            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
170            q.add(null);
171            shouldThrow();
172        } catch (NullPointerException success) {}
173    }
174
175    /**
173       * Offer succeeds if not full; fails if full
174       */
175      public void testOffer() {
# Line 182 | Line 179 | public class LinkedBlockingQueueTest ext
179      }
180  
181      /**
182 <     * add succeeds if not full; throws ISE if full
182 >     * add succeeds if not full; throws IllegalStateException if full
183       */
184      public void testAdd() {
185 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
186 +        for (int i = 0; i < SIZE; ++i)
187 +            assertTrue(q.add(new Integer(i)));
188 +        assertEquals(0, q.remainingCapacity());
189          try {
189            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
190            for (int i = 0; i < SIZE; ++i) {
191                assertTrue(q.add(new Integer(i)));
192            }
193            assertEquals(0, q.remainingCapacity());
190              q.add(new Integer(SIZE));
191              shouldThrow();
192          } catch (IllegalStateException success) {}
193      }
194  
195      /**
196 <     * addAll(null) throws NPE
201 <     */
202 <    public void testAddAll1() {
203 <        try {
204 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
205 <            q.addAll(null);
206 <            shouldThrow();
207 <        } catch (NullPointerException success) {}
208 <    }
209 <
210 <    /**
211 <     * addAll(this) throws IAE
196 >     * addAll(this) throws IllegalArgumentException
197       */
198      public void testAddAllSelf() {
199 +        LinkedBlockingQueue q = populatedQueue(SIZE);
200          try {
215            LinkedBlockingQueue q = populatedQueue(SIZE);
201              q.addAll(q);
202              shouldThrow();
203          } catch (IllegalArgumentException success) {}
204      }
205  
206      /**
222     * addAll of a collection with null elements throws NPE
223     */
224    public void testAddAll2() {
225        try {
226            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
227            Integer[] ints = new Integer[SIZE];
228            q.addAll(Arrays.asList(ints));
229            shouldThrow();
230        } catch (NullPointerException success) {}
231    }
232
233    /**
207       * addAll of a collection with any null elements throws NPE after
208       * possibly adding some elements
209       */
210      public void testAddAll3() {
211 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
212 +        Integer[] ints = new Integer[SIZE];
213 +        for (int i = 0; i < SIZE - 1; ++i)
214 +            ints[i] = new Integer(i);
215 +        Collection<Integer> elements = Arrays.asList(ints);
216          try {
217 <            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
240 <            Integer[] ints = new Integer[SIZE];
241 <            for (int i = 0; i < SIZE-1; ++i)
242 <                ints[i] = new Integer(i);
243 <            q.addAll(Arrays.asList(ints));
217 >            q.addAll(elements);
218              shouldThrow();
219          } catch (NullPointerException success) {}
220      }
221  
222      /**
223 <     * addAll throws ISE if not enough room
223 >     * addAll throws IllegalStateException if not enough room
224       */
225      public void testAddAll4() {
226 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE - 1);
227 +        Integer[] ints = new Integer[SIZE];
228 +        for (int i = 0; i < SIZE; ++i)
229 +            ints[i] = new Integer(i);
230 +        Collection<Integer> elements = Arrays.asList(ints);
231          try {
232 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
254 <            Integer[] ints = new Integer[SIZE];
255 <            for (int i = 0; i < SIZE; ++i)
256 <                ints[i] = new Integer(i);
257 <            q.addAll(Arrays.asList(ints));
232 >            q.addAll(elements);
233              shouldThrow();
234          } catch (IllegalStateException success) {}
235      }
# Line 275 | Line 250 | public class LinkedBlockingQueueTest ext
250      }
251  
252      /**
278     * put(null) throws NPE
279     */
280     public void testPutNull() throws InterruptedException {
281        try {
282            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
283            q.put(null);
284            shouldThrow();
285        } catch (NullPointerException success) {}
286     }
287
288    /**
253       * all elements successfully put are contained
254       */
255      public void testPut() throws InterruptedException {
256          LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
257          for (int i = 0; i < SIZE; ++i) {
258 <            Integer I = new Integer(i);
259 <            q.put(I);
260 <            assertTrue(q.contains(I));
258 >            Integer x = new Integer(i);
259 >            q.put(x);
260 >            assertTrue(q.contains(x));
261          }
262          assertEquals(0, q.remainingCapacity());
263      }
# Line 303 | Line 267 | public class LinkedBlockingQueueTest ext
267       */
268      public void testBlockingPut() throws InterruptedException {
269          final LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
270 <        Thread t = new Thread(new CheckedRunnable() {
270 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
271 >        Thread t = newStartedThread(new CheckedRunnable() {
272              public void realRun() throws InterruptedException {
273                  for (int i = 0; i < SIZE; ++i)
274                      q.put(i);
275                  assertEquals(SIZE, q.size());
276                  assertEquals(0, q.remainingCapacity());
277 +
278 +                Thread.currentThread().interrupt();
279 +                try {
280 +                    q.put(99);
281 +                    shouldThrow();
282 +                } catch (InterruptedException success) {}
283 +                assertFalse(Thread.interrupted());
284 +
285 +                pleaseInterrupt.countDown();
286                  try {
287                      q.put(99);
288                      shouldThrow();
289                  } catch (InterruptedException success) {}
290 +                assertFalse(Thread.interrupted());
291              }});
292  
293 <        t.start();
294 <        Thread.sleep(SHORT_DELAY_MS);
293 >        await(pleaseInterrupt);
294 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.WAITING);
295          t.interrupt();
296 <        t.join();
296 >        awaitTermination(t);
297          assertEquals(SIZE, q.size());
298          assertEquals(0, q.remainingCapacity());
299      }
300  
301      /**
302 <     * put blocks waiting for take when full
302 >     * put blocks interruptibly waiting for take when full
303       */
304      public void testPutWithTake() throws InterruptedException {
305          final int capacity = 2;
306          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
307 <        Thread t = new Thread(new CheckedRunnable() {
307 >        final CountDownLatch pleaseTake = new CountDownLatch(1);
308 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
309 >        Thread t = newStartedThread(new CheckedRunnable() {
310              public void realRun() throws InterruptedException {
311 <                for (int i = 0; i < capacity + 1; i++)
311 >                for (int i = 0; i < capacity; i++)
312                      q.put(i);
313 +                pleaseTake.countDown();
314 +                q.put(86);
315 +
316 +                Thread.currentThread().interrupt();
317 +                try {
318 +                    q.put(99);
319 +                    shouldThrow();
320 +                } catch (InterruptedException success) {}
321 +                assertFalse(Thread.interrupted());
322 +
323 +                pleaseInterrupt.countDown();
324                  try {
325                      q.put(99);
326                      shouldThrow();
327                  } catch (InterruptedException success) {}
328 +                assertFalse(Thread.interrupted());
329              }});
330  
331 <        t.start();
332 <        Thread.sleep(SHORT_DELAY_MS);
344 <        assertEquals(q.remainingCapacity(), 0);
331 >        await(pleaseTake);
332 >        assertEquals(0, q.remainingCapacity());
333          assertEquals(0, q.take());
334 <        Thread.sleep(SHORT_DELAY_MS);
334 >
335 >        await(pleaseInterrupt);
336 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.WAITING);
337          t.interrupt();
338 <        t.join();
339 <        assertEquals(q.remainingCapacity(), 0);
338 >        awaitTermination(t);
339 >        assertEquals(0, q.remainingCapacity());
340      }
341  
342      /**
343       * timed offer times out if full and elements not taken
344       */
345 <    public void testTimedOffer() throws InterruptedException {
345 >    public void testTimedOffer() {
346          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
347 <        Thread t = new Thread(new CheckedRunnable() {
347 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
348 >        Thread t = newStartedThread(new CheckedRunnable() {
349              public void realRun() throws InterruptedException {
350                  q.put(new Object());
351                  q.put(new Object());
352 <                assertFalse(q.offer(new Object(), SHORT_DELAY_MS, MILLISECONDS));
352 >                long startTime = System.nanoTime();
353 >
354 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
355 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
356 >
357 >                Thread.currentThread().interrupt();
358                  try {
359 <                    q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
359 >                    q.offer(new Object(), randomTimeout(), randomTimeUnit());
360                      shouldThrow();
361                  } catch (InterruptedException success) {}
362 +                assertFalse(Thread.interrupted());
363 +
364 +                pleaseInterrupt.countDown();
365 +                try {
366 +                    q.offer(new Object(), LONGER_DELAY_MS, MILLISECONDS);
367 +                    shouldThrow();
368 +                } catch (InterruptedException success) {}
369 +                assertFalse(Thread.interrupted());
370              }});
371  
372 <        t.start();
373 <        Thread.sleep(SMALL_DELAY_MS);
372 >        await(pleaseInterrupt);
373 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.TIMED_WAITING);
374          t.interrupt();
375 <        t.join();
375 >        awaitTermination(t);
376      }
377  
378      /**
# Line 385 | Line 389 | public class LinkedBlockingQueueTest ext
389       * Take removes existing elements until empty, then blocks interruptibly
390       */
391      public void testBlockingTake() throws InterruptedException {
392 <        final LinkedBlockingQueue q = populatedQueue(SIZE);
393 <        Thread t = new Thread(new CheckedRunnable() {
392 >        final BlockingQueue q = populatedQueue(SIZE);
393 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
394 >        Thread t = newStartedThread(new CheckedRunnable() {
395              public void realRun() throws InterruptedException {
396 <                for (int i = 0; i < SIZE; ++i) {
397 <                    assertEquals(i, q.take());
398 <                }
396 >                for (int i = 0; i < SIZE; i++) assertEquals(i, q.take());
397 >
398 >                Thread.currentThread().interrupt();
399 >                try {
400 >                    q.take();
401 >                    shouldThrow();
402 >                } catch (InterruptedException success) {}
403 >                assertFalse(Thread.interrupted());
404 >
405 >                pleaseInterrupt.countDown();
406                  try {
407                      q.take();
408                      shouldThrow();
409                  } catch (InterruptedException success) {}
410 +                assertFalse(Thread.interrupted());
411              }});
412  
413 <        t.start();
414 <        Thread.sleep(SHORT_DELAY_MS);
413 >        await(pleaseInterrupt);
414 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.WAITING);
415          t.interrupt();
416 <        t.join();
416 >        awaitTermination(t);
417      }
418  
419      /**
# Line 429 | Line 442 | public class LinkedBlockingQueueTest ext
442       * timed poll with nonzero timeout succeeds when non-empty, else times out
443       */
444      public void testTimedPoll() throws InterruptedException {
445 <        LinkedBlockingQueue q = populatedQueue(SIZE);
445 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
446          for (int i = 0; i < SIZE; ++i) {
447 <            assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
448 <        }
449 <        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
447 >            long startTime = System.nanoTime();
448 >            assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
449 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
450 >        }
451 >        long startTime = System.nanoTime();
452 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
453 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
454 >        checkEmpty(q);
455      }
456  
457      /**
# Line 441 | Line 459 | public class LinkedBlockingQueueTest ext
459       * returning timeout status
460       */
461      public void testInterruptedTimedPoll() throws InterruptedException {
462 <        Thread t = new Thread(new CheckedRunnable() {
462 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
463 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
464 >        Thread t = newStartedThread(new CheckedRunnable() {
465              public void realRun() throws InterruptedException {
466 <                LinkedBlockingQueue q = populatedQueue(SIZE);
467 <                for (int i = 0; i < SIZE; ++i) {
468 <                    assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
469 <                }
466 >                long startTime = System.nanoTime();
467 >                for (int i = 0; i < SIZE; i++)
468 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
469 >
470 >                Thread.currentThread().interrupt();
471 >                try {
472 >                    q.poll(randomTimeout(), randomTimeUnit());
473 >                    shouldThrow();
474 >                } catch (InterruptedException success) {}
475 >                assertFalse(Thread.interrupted());
476 >
477 >                pleaseInterrupt.countDown();
478                  try {
479 <                    q.poll(SMALL_DELAY_MS, MILLISECONDS);
479 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
480                      shouldThrow();
481                  } catch (InterruptedException success) {}
482 +                assertFalse(Thread.interrupted());
483 +
484 +                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
485              }});
486  
487 <        t.start();
488 <        Thread.sleep(SHORT_DELAY_MS);
487 >        await(pleaseInterrupt);
488 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.TIMED_WAITING);
489          t.interrupt();
490 <        t.join();
490 >        awaitTermination(t);
491 >        checkEmpty(q);
492      }
493  
494      /**
# Line 503 | Line 535 | public class LinkedBlockingQueueTest ext
535      }
536  
537      /**
506     * remove(x) removes x and returns true if present
507     */
508    public void testRemoveElement() {
509        LinkedBlockingQueue q = populatedQueue(SIZE);
510        for (int i = 1; i < SIZE; i+=2) {
511            assertTrue(q.contains(i));
512            assertTrue(q.remove(i));
513            assertFalse(q.contains(i));
514            assertTrue(q.contains(i-1));
515        }
516        for (int i = 0; i < SIZE; i+=2) {
517            assertTrue(q.contains(i));
518            assertTrue(q.remove(i));
519            assertFalse(q.contains(i));
520            assertFalse(q.remove(i+1));
521            assertFalse(q.contains(i+1));
522        }
523        assertTrue(q.isEmpty());
524    }
525
526    /**
538       * An add following remove(x) succeeds
539       */
540      public void testRemoveElementAndAdd() throws InterruptedException {
# Line 533 | Line 544 | public class LinkedBlockingQueueTest ext
544          assertTrue(q.remove(new Integer(1)));
545          assertTrue(q.remove(new Integer(2)));
546          assertTrue(q.add(new Integer(3)));
547 <        assertTrue(q.take() != null);
547 >        assertNotNull(q.take());
548      }
549  
550      /**
# Line 592 | Line 603 | public class LinkedBlockingQueueTest ext
603                  assertTrue(changed);
604  
605              assertTrue(q.containsAll(p));
606 <            assertEquals(SIZE-i, q.size());
606 >            assertEquals(SIZE - i, q.size());
607              p.remove();
608          }
609      }
# Line 605 | Line 616 | public class LinkedBlockingQueueTest ext
616              LinkedBlockingQueue q = populatedQueue(SIZE);
617              LinkedBlockingQueue p = populatedQueue(i);
618              assertTrue(q.removeAll(p));
619 <            assertEquals(SIZE-i, q.size());
619 >            assertEquals(SIZE - i, q.size());
620              for (int j = 0; j < i; ++j) {
621 <                Integer I = (Integer)(p.remove());
622 <                assertFalse(q.contains(I));
621 >                Integer x = (Integer)(p.remove());
622 >                assertFalse(q.contains(x));
623              }
624          }
625      }
# Line 618 | Line 629 | public class LinkedBlockingQueueTest ext
629       */
630      public void testToArray() {
631          LinkedBlockingQueue q = populatedQueue(SIZE);
632 <        Object[] o = q.toArray();
633 <        for (int i = 0; i < o.length; i++)
634 <            assertSame(o[i], q.poll());
632 >        Object[] a = q.toArray();
633 >        assertSame(Object[].class, a.getClass());
634 >        for (Object o : a)
635 >            assertSame(o, q.poll());
636 >        assertTrue(q.isEmpty());
637      }
638  
639      /**
# Line 631 | Line 644 | public class LinkedBlockingQueueTest ext
644          Integer[] ints = new Integer[SIZE];
645          Integer[] array = q.toArray(ints);
646          assertSame(ints, array);
647 <        for (int i = 0; i < ints.length; i++)
648 <            assertSame(ints[i], q.poll());
649 <    }
637 <
638 <    /**
639 <     * toArray(null) throws NullPointerException
640 <     */
641 <    public void testToArray_NullArg() {
642 <        LinkedBlockingQueue q = populatedQueue(SIZE);
643 <        try {
644 <            q.toArray(null);
645 <            shouldThrow();
646 <        } catch (NullPointerException success) {}
647 >        for (Integer o : ints)
648 >            assertSame(o, q.poll());
649 >        assertTrue(q.isEmpty());
650      }
651  
652      /**
# Line 657 | Line 660 | public class LinkedBlockingQueueTest ext
660          } catch (ArrayStoreException success) {}
661      }
662  
660
663      /**
664       * iterator iterates through all elements
665       */
666      public void testIterator() throws InterruptedException {
667          LinkedBlockingQueue q = populatedQueue(SIZE);
668          Iterator it = q.iterator();
669 <        while (it.hasNext()) {
669 >        int i;
670 >        for (i = 0; it.hasNext(); i++)
671 >            assertTrue(q.contains(it.next()));
672 >        assertEquals(i, SIZE);
673 >        assertIteratorExhausted(it);
674 >
675 >        it = q.iterator();
676 >        for (i = 0; it.hasNext(); i++)
677              assertEquals(it.next(), q.take());
678 <        }
678 >        assertEquals(i, SIZE);
679 >        assertIteratorExhausted(it);
680 >    }
681 >
682 >    /**
683 >     * iterator of empty collection has no elements
684 >     */
685 >    public void testEmptyIterator() {
686 >        assertIteratorExhausted(new LinkedBlockingQueue().iterator());
687      }
688  
689      /**
# Line 688 | Line 705 | public class LinkedBlockingQueueTest ext
705          assertFalse(it.hasNext());
706      }
707  
691
708      /**
709       * iterator ordering is FIFO
710       */
# Line 720 | Line 736 | public class LinkedBlockingQueueTest ext
736          assertEquals(0, q.size());
737      }
738  
723
739      /**
740       * toString contains toStrings of elements
741       */
# Line 728 | Line 743 | public class LinkedBlockingQueueTest ext
743          LinkedBlockingQueue q = populatedQueue(SIZE);
744          String s = q.toString();
745          for (int i = 0; i < SIZE; ++i) {
746 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
746 >            assertTrue(s.contains(String.valueOf(i)));
747          }
748      }
749  
735
750      /**
751       * offer transfers elements across Executor tasks
752       */
# Line 740 | Line 754 | public class LinkedBlockingQueueTest ext
754          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
755          q.add(one);
756          q.add(two);
757 <        ExecutorService executor = Executors.newFixedThreadPool(2);
758 <        executor.execute(new CheckedRunnable() {
759 <            public void realRun() throws InterruptedException {
760 <                assertFalse(q.offer(three));
761 <                assertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
762 <                assertEquals(0, q.remainingCapacity());
763 <            }});
764 <
765 <        executor.execute(new CheckedRunnable() {
766 <            public void realRun() throws InterruptedException {
767 <                Thread.sleep(SMALL_DELAY_MS);
768 <                assertSame(one, q.take());
769 <            }});
770 <
771 <        joinPool(executor);
757 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
758 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
759 >        try (PoolCleaner cleaner = cleaner(executor)) {
760 >            executor.execute(new CheckedRunnable() {
761 >                public void realRun() throws InterruptedException {
762 >                    assertFalse(q.offer(three));
763 >                    threadsStarted.await();
764 >                    assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
765 >                    assertEquals(0, q.remainingCapacity());
766 >                }});
767 >
768 >            executor.execute(new CheckedRunnable() {
769 >                public void realRun() throws InterruptedException {
770 >                    threadsStarted.await();
771 >                    assertSame(one, q.take());
772 >                }});
773 >        }
774      }
775  
776      /**
777 <     * poll retrieves elements across Executor threads
777 >     * timed poll retrieves elements across Executor threads
778       */
779      public void testPollInExecutor() {
780          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
781 <        ExecutorService executor = Executors.newFixedThreadPool(2);
782 <        executor.execute(new CheckedRunnable() {
783 <            public void realRun() throws InterruptedException {
784 <                assertNull(q.poll());
785 <                assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
786 <                assertTrue(q.isEmpty());
787 <            }});
788 <
789 <        executor.execute(new CheckedRunnable() {
790 <            public void realRun() throws InterruptedException {
791 <                Thread.sleep(SMALL_DELAY_MS);
792 <                q.put(one);
793 <            }});
794 <
795 <        joinPool(executor);
781 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
782 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
783 >        try (PoolCleaner cleaner = cleaner(executor)) {
784 >            executor.execute(new CheckedRunnable() {
785 >                public void realRun() throws InterruptedException {
786 >                    assertNull(q.poll());
787 >                    threadsStarted.await();
788 >                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
789 >                    checkEmpty(q);
790 >                }});
791 >
792 >            executor.execute(new CheckedRunnable() {
793 >                public void realRun() throws InterruptedException {
794 >                    threadsStarted.await();
795 >                    q.put(one);
796 >                }});
797 >        }
798      }
799  
800      /**
801 <     * A deserialized serialized queue has same elements in same order
801 >     * A deserialized/reserialized queue has same elements in same order
802       */
803      public void testSerialization() throws Exception {
804 <        LinkedBlockingQueue q = populatedQueue(SIZE);
805 <
788 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
789 <        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
790 <        out.writeObject(q);
791 <        out.close();
792 <
793 <        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
794 <        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
795 <        LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
796 <        assertEquals(q.size(), r.size());
797 <        while (!q.isEmpty())
798 <            assertEquals(q.remove(), r.remove());
799 <    }
800 <
801 <    /**
802 <     * drainTo(null) throws NPE
803 <     */
804 <    public void testDrainToNull() {
805 <        LinkedBlockingQueue q = populatedQueue(SIZE);
806 <        try {
807 <            q.drainTo(null);
808 <            shouldThrow();
809 <        } catch (NullPointerException success) {}
810 <    }
804 >        Queue x = populatedQueue(SIZE);
805 >        Queue y = serialClone(x);
806  
807 <    /**
808 <     * drainTo(this) throws IAE
809 <     */
810 <    public void testDrainToSelf() {
811 <        LinkedBlockingQueue q = populatedQueue(SIZE);
812 <        try {
813 <            q.drainTo(q);
814 <            shouldThrow();
815 <        } catch (IllegalArgumentException success) {}
807 >        assertNotSame(x, y);
808 >        assertEquals(x.size(), y.size());
809 >        assertEquals(x.toString(), y.toString());
810 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
811 >        while (!x.isEmpty()) {
812 >            assertFalse(y.isEmpty());
813 >            assertEquals(x.remove(), y.remove());
814 >        }
815 >        assertTrue(y.isEmpty());
816      }
817  
818      /**
# Line 827 | Line 822 | public class LinkedBlockingQueueTest ext
822          LinkedBlockingQueue q = populatedQueue(SIZE);
823          ArrayList l = new ArrayList();
824          q.drainTo(l);
825 <        assertEquals(q.size(), 0);
826 <        assertEquals(l.size(), SIZE);
825 >        assertEquals(0, q.size());
826 >        assertEquals(SIZE, l.size());
827          for (int i = 0; i < SIZE; ++i)
828              assertEquals(l.get(i), new Integer(i));
829          q.add(zero);
# Line 838 | Line 833 | public class LinkedBlockingQueueTest ext
833          assertTrue(q.contains(one));
834          l.clear();
835          q.drainTo(l);
836 <        assertEquals(q.size(), 0);
837 <        assertEquals(l.size(), 2);
836 >        assertEquals(0, q.size());
837 >        assertEquals(2, l.size());
838          for (int i = 0; i < 2; ++i)
839              assertEquals(l.get(i), new Integer(i));
840      }
# Line 851 | Line 846 | public class LinkedBlockingQueueTest ext
846          final LinkedBlockingQueue q = populatedQueue(SIZE);
847          Thread t = new Thread(new CheckedRunnable() {
848              public void realRun() throws InterruptedException {
849 <                q.put(new Integer(SIZE+1));
849 >                q.put(new Integer(SIZE + 1));
850              }});
851  
852          t.start();
# Line 865 | Line 860 | public class LinkedBlockingQueueTest ext
860      }
861  
862      /**
868     * drainTo(null, n) throws NPE
869     */
870    public void testDrainToNullN() {
871        LinkedBlockingQueue q = populatedQueue(SIZE);
872        try {
873            q.drainTo(null, 0);
874            shouldThrow();
875        } catch (NullPointerException success) {}
876    }
877
878    /**
879     * drainTo(this, n) throws IAE
880     */
881    public void testDrainToSelfN() {
882        LinkedBlockingQueue q = populatedQueue(SIZE);
883        try {
884            q.drainTo(q, 0);
885            shouldThrow();
886        } catch (IllegalArgumentException success) {}
887    }
888
889    /**
863       * drainTo(c, n) empties first min(n, size) elements of queue into c
864       */
865      public void testDrainToN() {
# Line 897 | Line 870 | public class LinkedBlockingQueueTest ext
870              ArrayList l = new ArrayList();
871              q.drainTo(l, i);
872              int k = (i < SIZE) ? i : SIZE;
873 <            assertEquals(l.size(), k);
874 <            assertEquals(q.size(), SIZE-k);
873 >            assertEquals(k, l.size());
874 >            assertEquals(SIZE - k, q.size());
875              for (int j = 0; j < k; ++j)
876                  assertEquals(l.get(j), new Integer(j));
877 <            while (q.poll() != null) ;
877 >            do {} while (q.poll() != null);
878 >        }
879 >    }
880 >
881 >    /**
882 >     * remove(null), contains(null) always return false
883 >     */
884 >    public void testNeverContainsNull() {
885 >        Collection<?>[] qs = {
886 >            new LinkedBlockingQueue<Object>(),
887 >            populatedQueue(2),
888 >        };
889 >
890 >        for (Collection<?> q : qs) {
891 >            assertFalse(q.contains(null));
892 >            assertFalse(q.remove(null));
893          }
894      }
895  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines