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.31 by jsr166, Tue Oct 19 00:43:49 2010 UTC vs.
Revision 1.79 by jsr166, Sun Aug 11 22:29:27 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 populatedQueue(int n) {
62 <        LinkedBlockingQueue q = new LinkedBlockingQueue(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 62 | 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];
90 <            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];
101 <            for (int i = 0; i < SIZE-1; ++i)
102 <                ints[i] = new Integer(i);
103 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
123 >            new LinkedBlockingQueue(elements);
124              shouldThrow();
125          } catch (NullPointerException success) {}
126      }
# Line 136 | 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      /**
153     * offer(null) throws NPE
154     */
155    public void testOfferNull() {
156        try {
157            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
158            q.offer(null);
159            shouldThrow();
160        } catch (NullPointerException success) {}
161    }
162
163    /**
164     * add(null) throws NPE
165     */
166    public void testAddNull() {
167        try {
168            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
169            q.add(null);
170            shouldThrow();
171        } catch (NullPointerException success) {}
172    }
173
174    /**
173       * Offer succeeds if not full; fails if full
174       */
175      public void testOffer() {
# Line 181 | 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 {
188            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
189            for (int i = 0; i < SIZE; ++i) {
190                assertTrue(q.add(new Integer(i)));
191            }
192            assertEquals(0, q.remainingCapacity());
190              q.add(new Integer(SIZE));
191              shouldThrow();
192          } catch (IllegalStateException success) {}
193      }
194  
195      /**
196 <     * addAll(null) throws NPE
200 <     */
201 <    public void testAddAll1() {
202 <        try {
203 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
204 <            q.addAll(null);
205 <            shouldThrow();
206 <        } catch (NullPointerException success) {}
207 <    }
208 <
209 <    /**
210 <     * addAll(this) throws IAE
196 >     * addAll(this) throws IllegalArgumentException
197       */
198      public void testAddAllSelf() {
199 +        LinkedBlockingQueue q = populatedQueue(SIZE);
200          try {
214            LinkedBlockingQueue q = populatedQueue(SIZE);
201              q.addAll(q);
202              shouldThrow();
203          } catch (IllegalArgumentException success) {}
204      }
205  
206      /**
221     * addAll of a collection with null elements throws NPE
222     */
223    public void testAddAll2() {
224        try {
225            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
226            Integer[] ints = new Integer[SIZE];
227            q.addAll(Arrays.asList(ints));
228            shouldThrow();
229        } catch (NullPointerException success) {}
230    }
231
232    /**
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);
239 <            Integer[] ints = new Integer[SIZE];
240 <            for (int i = 0; i < SIZE-1; ++i)
241 <                ints[i] = new Integer(i);
242 <            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);
253 <            Integer[] ints = new Integer[SIZE];
254 <            for (int i = 0; i < SIZE; ++i)
255 <                ints[i] = new Integer(i);
256 <            q.addAll(Arrays.asList(ints));
232 >            q.addAll(elements);
233              shouldThrow();
234          } catch (IllegalStateException success) {}
235      }
# Line 274 | Line 250 | public class LinkedBlockingQueueTest ext
250      }
251  
252      /**
277     * put(null) throws NPE
278     */
279     public void testPutNull() throws InterruptedException {
280        try {
281            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
282            q.put(null);
283            shouldThrow();
284        } catch (NullPointerException success) {}
285     }
286
287    /**
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 302 | 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);
343 <        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(), randomTimeout(), randomTimeUnit());
360 >                    shouldThrow();
361 >                } catch (InterruptedException success) {}
362 >                assertFalse(Thread.interrupted());
363 >
364 >                pleaseInterrupt.countDown();
365                  try {
366                      q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
367                      shouldThrow();
368                  } catch (InterruptedException success) {}
369 +                assertFalse(Thread.interrupted());
370 +
371 +                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
372              }});
373  
374 <        t.start();
375 <        Thread.sleep(SMALL_DELAY_MS);
374 >        await(pleaseInterrupt);
375 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.TIMED_WAITING);
376          t.interrupt();
377 <        t.join();
377 >        awaitTermination(t);
378      }
379  
380      /**
# Line 381 | Line 388 | public class LinkedBlockingQueueTest ext
388      }
389  
390      /**
384     * take blocks interruptibly when empty
385     */
386    public void testTakeFromEmpty() throws InterruptedException {
387        final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
388        Thread t = new ThreadShouldThrow(InterruptedException.class) {
389            public void realRun() throws InterruptedException {
390                q.take();
391            }};
392
393        t.start();
394        Thread.sleep(SHORT_DELAY_MS);
395        t.interrupt();
396        t.join();
397    }
398
399    /**
391       * Take removes existing elements until empty, then blocks interruptibly
392       */
393      public void testBlockingTake() throws InterruptedException {
394 <        final LinkedBlockingQueue q = populatedQueue(SIZE);
395 <        Thread t = new Thread(new CheckedRunnable() {
394 >        final BlockingQueue q = populatedQueue(SIZE);
395 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
396 >        Thread t = newStartedThread(new CheckedRunnable() {
397              public void realRun() throws InterruptedException {
398 <                for (int i = 0; i < SIZE; ++i) {
399 <                    assertEquals(i, q.take());
400 <                }
398 >                for (int i = 0; i < SIZE; i++) assertEquals(i, q.take());
399 >
400 >                Thread.currentThread().interrupt();
401 >                try {
402 >                    q.take();
403 >                    shouldThrow();
404 >                } catch (InterruptedException success) {}
405 >                assertFalse(Thread.interrupted());
406 >
407 >                pleaseInterrupt.countDown();
408                  try {
409                      q.take();
410                      shouldThrow();
411                  } catch (InterruptedException success) {}
412 +                assertFalse(Thread.interrupted());
413              }});
414  
415 <        t.start();
416 <        Thread.sleep(SHORT_DELAY_MS);
415 >        await(pleaseInterrupt);
416 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.WAITING);
417          t.interrupt();
418 <        t.join();
418 >        awaitTermination(t);
419      }
420  
421      /**
# Line 430 | Line 430 | public class LinkedBlockingQueueTest ext
430      }
431  
432      /**
433 <     * timed pool with zero timeout succeeds when non-empty, else times out
433 >     * timed poll with zero timeout succeeds when non-empty, else times out
434       */
435      public void testTimedPoll0() throws InterruptedException {
436          LinkedBlockingQueue q = populatedQueue(SIZE);
# Line 441 | Line 441 | public class LinkedBlockingQueueTest ext
441      }
442  
443      /**
444 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
444 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
445       */
446      public void testTimedPoll() throws InterruptedException {
447 <        LinkedBlockingQueue q = populatedQueue(SIZE);
447 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
448          for (int i = 0; i < SIZE; ++i) {
449 <            assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
450 <        }
451 <        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
449 >            long startTime = System.nanoTime();
450 >            assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
451 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
452 >        }
453 >        long startTime = System.nanoTime();
454 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
455 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
456 >        checkEmpty(q);
457      }
458  
459      /**
# Line 456 | Line 461 | public class LinkedBlockingQueueTest ext
461       * returning timeout status
462       */
463      public void testInterruptedTimedPoll() throws InterruptedException {
464 <        Thread t = new Thread(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 <                }
464 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
465 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
466 >        Thread t = newStartedThread(new CheckedRunnable() {
467 >            public void realRun() throws InterruptedException {
468 >                long startTime = System.nanoTime();
469 >                for (int i = 0; i < SIZE; i++)
470 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
471 >
472 >                Thread.currentThread().interrupt();
473 >                try {
474 >                    q.poll(randomTimeout(), randomTimeUnit());
475 >                    shouldThrow();
476 >                } catch (InterruptedException success) {}
477 >                assertFalse(Thread.interrupted());
478 >
479 >                pleaseInterrupt.countDown();
480                  try {
481 <                    q.poll(SMALL_DELAY_MS, MILLISECONDS);
481 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
482                      shouldThrow();
483                  } catch (InterruptedException success) {}
484 +                assertFalse(Thread.interrupted());
485 +
486 +                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
487              }});
488  
489 <        t.start();
490 <        Thread.sleep(SHORT_DELAY_MS);
489 >        await(pleaseInterrupt);
490 >        if (randomBoolean()) assertThreadBlocks(t, Thread.State.TIMED_WAITING);
491          t.interrupt();
492 <        t.join();
492 >        awaitTermination(t);
493 >        checkEmpty(q);
494      }
495  
496      /**
# Line 518 | Line 537 | public class LinkedBlockingQueueTest ext
537      }
538  
539      /**
521     * remove(x) removes x and returns true if present
522     */
523    public void testRemoveElement() {
524        LinkedBlockingQueue q = populatedQueue(SIZE);
525        for (int i = 1; i < SIZE; i+=2) {
526            assertTrue(q.remove(new Integer(i)));
527        }
528        for (int i = 0; i < SIZE; i+=2) {
529            assertTrue(q.remove(new Integer(i)));
530            assertFalse(q.remove(new Integer(i+1)));
531        }
532        assertTrue(q.isEmpty());
533    }
534
535    /**
540       * An add following remove(x) succeeds
541       */
542      public void testRemoveElementAndAdd() throws InterruptedException {
# Line 542 | Line 546 | public class LinkedBlockingQueueTest ext
546          assertTrue(q.remove(new Integer(1)));
547          assertTrue(q.remove(new Integer(2)));
548          assertTrue(q.add(new Integer(3)));
549 <        assertTrue(q.take() != null);
549 >        assertNotNull(q.take());
550      }
551  
552      /**
# Line 601 | Line 605 | public class LinkedBlockingQueueTest ext
605                  assertTrue(changed);
606  
607              assertTrue(q.containsAll(p));
608 <            assertEquals(SIZE-i, q.size());
608 >            assertEquals(SIZE - i, q.size());
609              p.remove();
610          }
611      }
# Line 614 | Line 618 | public class LinkedBlockingQueueTest ext
618              LinkedBlockingQueue q = populatedQueue(SIZE);
619              LinkedBlockingQueue p = populatedQueue(i);
620              assertTrue(q.removeAll(p));
621 <            assertEquals(SIZE-i, q.size());
621 >            assertEquals(SIZE - i, q.size());
622              for (int j = 0; j < i; ++j) {
623 <                Integer I = (Integer)(p.remove());
624 <                assertFalse(q.contains(I));
623 >                Integer x = (Integer)(p.remove());
624 >                assertFalse(q.contains(x));
625              }
626          }
627      }
628  
629      /**
630 <     * toArray contains all elements
630 >     * toArray contains all elements in FIFO order
631       */
632 <    public void testToArray() throws InterruptedException {
632 >    public void testToArray() {
633          LinkedBlockingQueue q = populatedQueue(SIZE);
634 <        Object[] o = q.toArray();
635 <        for (int i = 0; i < o.length; i++)
636 <            assertEquals(o[i], q.take());
634 >        Object[] a = q.toArray();
635 >        assertSame(Object[].class, a.getClass());
636 >        for (Object o : a)
637 >            assertSame(o, q.poll());
638 >        assertTrue(q.isEmpty());
639      }
640  
641      /**
642 <     * toArray(a) contains all elements
642 >     * toArray(a) contains all elements in FIFO order
643       */
644      public void testToArray2() throws InterruptedException {
645 <        LinkedBlockingQueue q = populatedQueue(SIZE);
645 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
646          Integer[] ints = new Integer[SIZE];
647 <        ints = (Integer[])q.toArray(ints);
648 <        for (int i = 0; i < ints.length; i++)
649 <            assertEquals(ints[i], q.take());
650 <    }
651 <
646 <    /**
647 <     * toArray(null) throws NPE
648 <     */
649 <    public void testToArray_BadArg() {
650 <        LinkedBlockingQueue q = populatedQueue(SIZE);
651 <        try {
652 <            Object o[] = q.toArray(null);
653 <            shouldThrow();
654 <        } catch (NullPointerException success) {}
647 >        Integer[] array = q.toArray(ints);
648 >        assertSame(ints, array);
649 >        for (Integer o : ints)
650 >            assertSame(o, q.poll());
651 >        assertTrue(q.isEmpty());
652      }
653  
654      /**
655 <     * toArray with incompatible array type throws CCE
655 >     * toArray(incompatible array type) throws ArrayStoreException
656       */
657      public void testToArray1_BadArg() {
658          LinkedBlockingQueue q = populatedQueue(SIZE);
659          try {
660 <            Object o[] = q.toArray(new String[10]);
660 >            q.toArray(new String[10]);
661              shouldThrow();
662          } catch (ArrayStoreException success) {}
663      }
664  
668
665      /**
666       * iterator iterates through all elements
667       */
668      public void testIterator() throws InterruptedException {
669          LinkedBlockingQueue q = populatedQueue(SIZE);
670          Iterator it = q.iterator();
671 <        while (it.hasNext()) {
671 >        int i;
672 >        for (i = 0; it.hasNext(); i++)
673 >            assertTrue(q.contains(it.next()));
674 >        assertEquals(i, SIZE);
675 >        assertIteratorExhausted(it);
676 >
677 >        it = q.iterator();
678 >        for (i = 0; it.hasNext(); i++)
679              assertEquals(it.next(), q.take());
680 <        }
680 >        assertEquals(i, SIZE);
681 >        assertIteratorExhausted(it);
682 >    }
683 >
684 >    /**
685 >     * iterator of empty collection has no elements
686 >     */
687 >    public void testEmptyIterator() {
688 >        assertIteratorExhausted(new LinkedBlockingQueue().iterator());
689      }
690  
691      /**
# Line 696 | Line 707 | public class LinkedBlockingQueueTest ext
707          assertFalse(it.hasNext());
708      }
709  
699
710      /**
711       * iterator ordering is FIFO
712       */
# Line 728 | Line 738 | public class LinkedBlockingQueueTest ext
738          assertEquals(0, q.size());
739      }
740  
731
741      /**
742       * toString contains toStrings of elements
743       */
# Line 736 | Line 745 | public class LinkedBlockingQueueTest ext
745          LinkedBlockingQueue q = populatedQueue(SIZE);
746          String s = q.toString();
747          for (int i = 0; i < SIZE; ++i) {
748 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
748 >            assertTrue(s.contains(String.valueOf(i)));
749          }
750      }
751  
743
752      /**
753       * offer transfers elements across Executor tasks
754       */
# Line 748 | Line 756 | public class LinkedBlockingQueueTest ext
756          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
757          q.add(one);
758          q.add(two);
759 <        ExecutorService executor = Executors.newFixedThreadPool(2);
760 <        executor.execute(new CheckedRunnable() {
761 <            public void realRun() throws InterruptedException {
762 <                assertFalse(q.offer(three));
763 <                assertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
764 <                assertEquals(0, q.remainingCapacity());
765 <            }});
766 <
767 <        executor.execute(new CheckedRunnable() {
768 <            public void realRun() throws InterruptedException {
769 <                Thread.sleep(SMALL_DELAY_MS);
770 <                assertSame(one, q.take());
771 <            }});
772 <
773 <        joinPool(executor);
759 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
760 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
761 >        try (PoolCleaner cleaner = cleaner(executor)) {
762 >            executor.execute(new CheckedRunnable() {
763 >                public void realRun() throws InterruptedException {
764 >                    assertFalse(q.offer(three));
765 >                    threadsStarted.await();
766 >                    assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
767 >                    assertEquals(0, q.remainingCapacity());
768 >                }});
769 >
770 >            executor.execute(new CheckedRunnable() {
771 >                public void realRun() throws InterruptedException {
772 >                    threadsStarted.await();
773 >                    assertSame(one, q.take());
774 >                }});
775 >        }
776      }
777  
778      /**
779 <     * poll retrieves elements across Executor threads
779 >     * timed poll retrieves elements across Executor threads
780       */
781      public void testPollInExecutor() {
782          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
783 <        ExecutorService executor = Executors.newFixedThreadPool(2);
784 <        executor.execute(new CheckedRunnable() {
785 <            public void realRun() throws InterruptedException {
786 <                assertNull(q.poll());
787 <                assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
788 <                assertTrue(q.isEmpty());
789 <            }});
790 <
791 <        executor.execute(new CheckedRunnable() {
792 <            public void realRun() throws InterruptedException {
793 <                Thread.sleep(SMALL_DELAY_MS);
794 <                q.put(one);
795 <            }});
796 <
797 <        joinPool(executor);
783 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
784 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
785 >        try (PoolCleaner cleaner = cleaner(executor)) {
786 >            executor.execute(new CheckedRunnable() {
787 >                public void realRun() throws InterruptedException {
788 >                    assertNull(q.poll());
789 >                    threadsStarted.await();
790 >                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
791 >                    checkEmpty(q);
792 >                }});
793 >
794 >            executor.execute(new CheckedRunnable() {
795 >                public void realRun() throws InterruptedException {
796 >                    threadsStarted.await();
797 >                    q.put(one);
798 >                }});
799 >        }
800      }
801  
802      /**
803 <     * A deserialized serialized queue has same elements in same order
803 >     * A deserialized/reserialized queue has same elements in same order
804       */
805      public void testSerialization() throws Exception {
806 <        LinkedBlockingQueue q = populatedQueue(SIZE);
807 <
796 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
797 <        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
798 <        out.writeObject(q);
799 <        out.close();
800 <
801 <        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
802 <        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
803 <        LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
804 <        assertEquals(q.size(), r.size());
805 <        while (!q.isEmpty())
806 <            assertEquals(q.remove(), r.remove());
807 <    }
808 <
809 <    /**
810 <     * drainTo(null) throws NPE
811 <     */
812 <    public void testDrainToNull() {
813 <        LinkedBlockingQueue q = populatedQueue(SIZE);
814 <        try {
815 <            q.drainTo(null);
816 <            shouldThrow();
817 <        } catch (NullPointerException success) {}
818 <    }
806 >        Queue x = populatedQueue(SIZE);
807 >        Queue y = serialClone(x);
808  
809 <    /**
810 <     * drainTo(this) throws IAE
811 <     */
812 <    public void testDrainToSelf() {
813 <        LinkedBlockingQueue q = populatedQueue(SIZE);
814 <        try {
815 <            q.drainTo(q);
816 <            shouldThrow();
817 <        } catch (IllegalArgumentException success) {}
809 >        assertNotSame(x, y);
810 >        assertEquals(x.size(), y.size());
811 >        assertEquals(x.toString(), y.toString());
812 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
813 >        while (!x.isEmpty()) {
814 >            assertFalse(y.isEmpty());
815 >            assertEquals(x.remove(), y.remove());
816 >        }
817 >        assertTrue(y.isEmpty());
818      }
819  
820      /**
# Line 835 | Line 824 | public class LinkedBlockingQueueTest ext
824          LinkedBlockingQueue q = populatedQueue(SIZE);
825          ArrayList l = new ArrayList();
826          q.drainTo(l);
827 <        assertEquals(q.size(), 0);
828 <        assertEquals(l.size(), SIZE);
827 >        assertEquals(0, q.size());
828 >        assertEquals(SIZE, l.size());
829          for (int i = 0; i < SIZE; ++i)
830              assertEquals(l.get(i), new Integer(i));
831          q.add(zero);
# Line 846 | Line 835 | public class LinkedBlockingQueueTest ext
835          assertTrue(q.contains(one));
836          l.clear();
837          q.drainTo(l);
838 <        assertEquals(q.size(), 0);
839 <        assertEquals(l.size(), 2);
838 >        assertEquals(0, q.size());
839 >        assertEquals(2, l.size());
840          for (int i = 0; i < 2; ++i)
841              assertEquals(l.get(i), new Integer(i));
842      }
# Line 859 | Line 848 | public class LinkedBlockingQueueTest ext
848          final LinkedBlockingQueue q = populatedQueue(SIZE);
849          Thread t = new Thread(new CheckedRunnable() {
850              public void realRun() throws InterruptedException {
851 <                q.put(new Integer(SIZE+1));
851 >                q.put(new Integer(SIZE + 1));
852              }});
853  
854          t.start();
# Line 873 | Line 862 | public class LinkedBlockingQueueTest ext
862      }
863  
864      /**
876     * drainTo(null, n) throws NPE
877     */
878    public void testDrainToNullN() {
879        LinkedBlockingQueue q = populatedQueue(SIZE);
880        try {
881            q.drainTo(null, 0);
882            shouldThrow();
883        } catch (NullPointerException success) {}
884    }
885
886    /**
887     * drainTo(this, n) throws IAE
888     */
889    public void testDrainToSelfN() {
890        LinkedBlockingQueue q = populatedQueue(SIZE);
891        try {
892            q.drainTo(q, 0);
893            shouldThrow();
894        } catch (IllegalArgumentException success) {}
895    }
896
897    /**
865       * drainTo(c, n) empties first min(n, size) elements of queue into c
866       */
867      public void testDrainToN() {
# Line 905 | Line 872 | public class LinkedBlockingQueueTest ext
872              ArrayList l = new ArrayList();
873              q.drainTo(l, i);
874              int k = (i < SIZE) ? i : SIZE;
875 <            assertEquals(l.size(), k);
876 <            assertEquals(q.size(), SIZE-k);
875 >            assertEquals(k, l.size());
876 >            assertEquals(SIZE - k, q.size());
877              for (int j = 0; j < k; ++j)
878                  assertEquals(l.get(j), new Integer(j));
879 <            while (q.poll() != null) ;
879 >            do {} while (q.poll() != null);
880 >        }
881 >    }
882 >
883 >    /**
884 >     * remove(null), contains(null) always return false
885 >     */
886 >    public void testNeverContainsNull() {
887 >        Collection<?>[] qs = {
888 >            new LinkedBlockingQueue<Object>(),
889 >            populatedQueue(2),
890 >        };
891 >
892 >        for (Collection<?> q : qs) {
893 >            assertFalse(q.contains(null));
894 >            assertFalse(q.remove(null));
895          }
896      }
897  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines