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

Comparing jsr166/src/test/tck/ArrayBlockingQueueTest.java (file contents):
Revision 1.19 by jsr166, Sat Nov 21 10:29:49 2009 UTC vs.
Revision 1.59 by jsr166, Wed Dec 31 19:21:20 2014 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
10 import junit.framework.*;
11 import java.util.*;
12 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.ArrayBlockingQueue;
18 > import java.util.concurrent.BlockingQueue;
19 > import java.util.concurrent.CountDownLatch;
20 > import java.util.concurrent.Executors;
21 > import java.util.concurrent.ExecutorService;
22 >
23 > import junit.framework.Test;
24  
25   public class ArrayBlockingQueueTest extends JSR166TestCase {
26 +
27 +    public static class Fair extends BlockingQueueTest {
28 +        protected BlockingQueue emptyCollection() {
29 +            return new ArrayBlockingQueue(SIZE, true);
30 +        }
31 +    }
32 +
33 +    public static class NonFair extends BlockingQueueTest {
34 +        protected BlockingQueue emptyCollection() {
35 +            return new ArrayBlockingQueue(SIZE, false);
36 +        }
37 +    }
38 +
39      public static void main(String[] args) {
40 <        junit.textui.TestRunner.run (suite());
40 >        junit.textui.TestRunner.run(suite());
41      }
42 +
43      public static Test suite() {
44 <        return new TestSuite(ArrayBlockingQueueTest.class);
44 >        return newTestSuite(ArrayBlockingQueueTest.class,
45 >                            new Fair().testSuite(),
46 >                            new NonFair().testSuite());
47      }
48  
49      /**
50 <     * Create a queue of given size containing consecutive
50 >     * Returns a new queue of given size containing consecutive
51       * Integers 0 ... n.
52       */
53 <    private ArrayBlockingQueue populatedQueue(int n) {
54 <        ArrayBlockingQueue q = new ArrayBlockingQueue(n);
53 >    private ArrayBlockingQueue<Integer> populatedQueue(int n) {
54 >        ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(n);
55          assertTrue(q.isEmpty());
56          for (int i = 0; i < n; i++)
57              assertTrue(q.offer(new Integer(i)));
# Line 48 | Line 73 | public class ArrayBlockingQueueTest exte
73       */
74      public void testConstructor2() {
75          try {
76 <            ArrayBlockingQueue q = new ArrayBlockingQueue(0);
76 >            new ArrayBlockingQueue(0);
77              shouldThrow();
78          } catch (IllegalArgumentException success) {}
79      }
# Line 58 | Line 83 | public class ArrayBlockingQueueTest exte
83       */
84      public void testConstructor3() {
85          try {
86 <            ArrayBlockingQueue q = new ArrayBlockingQueue(1, true, null);
86 >            new ArrayBlockingQueue(1, true, null);
87              shouldThrow();
88          } catch (NullPointerException success) {}
89      }
# Line 67 | Line 92 | public class ArrayBlockingQueueTest exte
92       * Initializing from Collection of null elements throws NPE
93       */
94      public void testConstructor4() {
95 +        Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
96          try {
97 <            Integer[] ints = new Integer[SIZE];
72 <            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
97 >            new ArrayBlockingQueue(SIZE, false, elements);
98              shouldThrow();
99          } catch (NullPointerException success) {}
100      }
# Line 78 | Line 103 | public class ArrayBlockingQueueTest exte
103       * Initializing from Collection with some null elements throws NPE
104       */
105      public void testConstructor5() {
106 +        Integer[] ints = new Integer[SIZE];
107 +        for (int i = 0; i < SIZE-1; ++i)
108 +            ints[i] = i;
109 +        Collection<Integer> elements = Arrays.asList(ints);
110          try {
111 <            Integer[] ints = new Integer[SIZE];
83 <            for (int i = 0; i < SIZE-1; ++i)
84 <                ints[i] = new Integer(i);
85 <            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
111 >            new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
112              shouldThrow();
113          } catch (NullPointerException success) {}
114      }
# Line 91 | Line 117 | public class ArrayBlockingQueueTest exte
117       * Initializing from too large collection throws IAE
118       */
119      public void testConstructor6() {
120 +        Integer[] ints = new Integer[SIZE];
121 +        for (int i = 0; i < SIZE; ++i)
122 +            ints[i] = i;
123 +        Collection<Integer> elements = Arrays.asList(ints);
124          try {
125 <            Integer[] ints = new Integer[SIZE];
96 <            for (int i = 0; i < SIZE; ++i)
97 <                ints[i] = new Integer(i);
98 <            ArrayBlockingQueue q = new ArrayBlockingQueue(1, false, Arrays.asList(ints));
125 >            new ArrayBlockingQueue(SIZE - 1, false, elements);
126              shouldThrow();
127          } catch (IllegalArgumentException success) {}
128      }
# Line 106 | Line 133 | public class ArrayBlockingQueueTest exte
133      public void testConstructor7() {
134          Integer[] ints = new Integer[SIZE];
135          for (int i = 0; i < SIZE; ++i)
136 <            ints[i] = new Integer(i);
137 <        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, Arrays.asList(ints));
136 >            ints[i] = i;
137 >        Collection<Integer> elements = Arrays.asList(ints);
138 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, elements);
139          for (int i = 0; i < SIZE; ++i)
140              assertEquals(ints[i], q.poll());
141      }
# Line 145 | Line 173 | public class ArrayBlockingQueueTest exte
173      }
174  
175      /**
148     *  offer(null) throws NPE
149     */
150    public void testOfferNull() {
151        try {
152            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
153            q.offer(null);
154            shouldThrow();
155        } catch (NullPointerException success) {}
156    }
157
158    /**
159     *  add(null) throws NPE
160     */
161    public void testAddNull() {
162        try {
163            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
164            q.add(null);
165            shouldThrow();
166        } catch (NullPointerException success) {}
167    }
168
169    /**
176       * Offer succeeds if not full; fails if full
177       */
178      public void testOffer() {
# Line 191 | Line 197 | public class ArrayBlockingQueueTest exte
197      }
198  
199      /**
194     *  addAll(null) throws NPE
195     */
196    public void testAddAll1() {
197        try {
198            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
199            q.addAll(null);
200            shouldThrow();
201        } catch (NullPointerException success) {}
202    }
203
204    /**
200       * addAll(this) throws IAE
201       */
202      public void testAddAllSelf() {
# Line 212 | Line 207 | public class ArrayBlockingQueueTest exte
207          } catch (IllegalArgumentException success) {}
208      }
209  
215
216    /**
217     *  addAll of a collection with null elements throws NPE
218     */
219    public void testAddAll2() {
220        try {
221            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
222            Integer[] ints = new Integer[SIZE];
223            q.addAll(Arrays.asList(ints));
224            shouldThrow();
225        } catch (NullPointerException success) {}
226    }
210      /**
211       * addAll of a collection with any null elements throws NPE after
212       * possibly adding some elements
# Line 238 | Line 221 | public class ArrayBlockingQueueTest exte
221              shouldThrow();
222          } catch (NullPointerException success) {}
223      }
224 +
225      /**
226       * addAll throws ISE if not enough room
227       */
# Line 251 | Line 235 | public class ArrayBlockingQueueTest exte
235              shouldThrow();
236          } catch (IllegalStateException success) {}
237      }
238 +
239      /**
240       * Queue contains all elements, in traversal order, of successful addAll
241       */
# Line 267 | Line 252 | public class ArrayBlockingQueueTest exte
252      }
253  
254      /**
270     *  put(null) throws NPE
271     */
272    public void testPutNull() throws InterruptedException {
273        try {
274            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
275            q.put(null);
276            shouldThrow();
277        } catch (NullPointerException success) {}
278     }
279
280    /**
255       * all elements successfully put are contained
256       */
257      public void testPut() throws InterruptedException {
# Line 295 | Line 269 | public class ArrayBlockingQueueTest exte
269       */
270      public void testBlockingPut() throws InterruptedException {
271          final ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
272 <        Thread t = new Thread(new CheckedRunnable() {
273 <            public void realRun() {
274 <                int added = 0;
272 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
273 >        Thread t = newStartedThread(new CheckedRunnable() {
274 >            public void realRun() throws InterruptedException {
275 >                for (int i = 0; i < SIZE; ++i)
276 >                    q.put(i);
277 >                assertEquals(SIZE, q.size());
278 >                assertEquals(0, q.remainingCapacity());
279 >
280 >                Thread.currentThread().interrupt();
281                  try {
282 <                    for (int i = 0; i < SIZE; ++i) {
283 <                        q.put(new Integer(i));
284 <                        ++added;
285 <                    }
306 <                    q.put(new Integer(SIZE));
307 <                    threadShouldThrow();
308 <                } catch (InterruptedException ie) {
309 <                    threadAssertEquals(added, SIZE);
310 <                }}});
282 >                    q.put(99);
283 >                    shouldThrow();
284 >                } catch (InterruptedException success) {}
285 >                assertFalse(Thread.interrupted());
286  
287 <        t.start();
288 <        Thread.sleep(MEDIUM_DELAY_MS);
287 >                pleaseInterrupt.countDown();
288 >                try {
289 >                    q.put(99);
290 >                    shouldThrow();
291 >                } catch (InterruptedException success) {}
292 >                assertFalse(Thread.interrupted());
293 >            }});
294 >
295 >        await(pleaseInterrupt);
296 >        assertThreadStaysAlive(t);
297          t.interrupt();
298 <        t.join();
298 >        awaitTermination(t);
299 >        assertEquals(SIZE, q.size());
300 >        assertEquals(0, q.remainingCapacity());
301      }
302  
303      /**
304 <     * put blocks waiting for take when full
304 >     * put blocks interruptibly waiting for take when full
305       */
306      public void testPutWithTake() throws InterruptedException {
307 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
308 <        Thread t = new Thread(new CheckedRunnable() {
309 <            public void realRun() {
310 <                int added = 0;
307 >        final int capacity = 2;
308 >        final ArrayBlockingQueue q = new ArrayBlockingQueue(capacity);
309 >        final CountDownLatch pleaseTake = new CountDownLatch(1);
310 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
311 >        Thread t = newStartedThread(new CheckedRunnable() {
312 >            public void realRun() throws InterruptedException {
313 >                for (int i = 0; i < capacity; i++)
314 >                    q.put(i);
315 >                pleaseTake.countDown();
316 >                q.put(86);
317 >
318 >                pleaseInterrupt.countDown();
319                  try {
320 <                    q.put(new Object());
321 <                    ++added;
322 <                    q.put(new Object());
323 <                    ++added;
331 <                    q.put(new Object());
332 <                    ++added;
333 <                    q.put(new Object());
334 <                    ++added;
335 <                    threadShouldThrow();
336 <                } catch (InterruptedException e) {
337 <                    threadAssertTrue(added >= 2);
338 <                }
320 >                    q.put(99);
321 >                    shouldThrow();
322 >                } catch (InterruptedException success) {}
323 >                assertFalse(Thread.interrupted());
324              }});
325  
326 <        t.start();
327 <        Thread.sleep(SHORT_DELAY_MS);
328 <        q.take();
326 >        await(pleaseTake);
327 >        assertEquals(0, q.remainingCapacity());
328 >        assertEquals(0, q.take());
329 >
330 >        await(pleaseInterrupt);
331 >        assertThreadStaysAlive(t);
332          t.interrupt();
333 <        t.join();
333 >        awaitTermination(t);
334 >        assertEquals(0, q.remainingCapacity());
335      }
336  
337      /**
# Line 350 | Line 339 | public class ArrayBlockingQueueTest exte
339       */
340      public void testTimedOffer() throws InterruptedException {
341          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
342 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
342 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
343 >        Thread t = newStartedThread(new CheckedRunnable() {
344              public void realRun() throws InterruptedException {
345                  q.put(new Object());
346                  q.put(new Object());
347 <                threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS/2, MILLISECONDS));
348 <                q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
349 <            }};
347 >                long startTime = System.nanoTime();
348 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
349 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
350 >                pleaseInterrupt.countDown();
351 >                try {
352 >                    q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
353 >                    shouldThrow();
354 >                } catch (InterruptedException success) {}
355 >            }});
356  
357 <        t.start();
358 <        Thread.sleep(SHORT_DELAY_MS);
357 >        await(pleaseInterrupt);
358 >        assertThreadStaysAlive(t);
359          t.interrupt();
360 <        t.join();
360 >        awaitTermination(t);
361      }
362  
363      /**
# Line 370 | Line 366 | public class ArrayBlockingQueueTest exte
366      public void testTake() throws InterruptedException {
367          ArrayBlockingQueue q = populatedQueue(SIZE);
368          for (int i = 0; i < SIZE; ++i) {
369 <            assertEquals(i, ((Integer)q.take()).intValue());
369 >            assertEquals(i, q.take());
370          }
371      }
372  
373      /**
378     * take blocks interruptibly when empty
379     */
380    public void testTakeFromEmpty() throws InterruptedException {
381        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
382        Thread t = new ThreadShouldThrow(InterruptedException.class) {
383            public void realRun() throws InterruptedException {
384                q.take();
385            }};
386
387        t.start();
388        Thread.sleep(SHORT_DELAY_MS);
389        t.interrupt();
390        t.join();
391    }
392
393    /**
374       * Take removes existing elements until empty, then blocks interruptibly
375       */
376      public void testBlockingTake() throws InterruptedException {
377 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
377 >        final ArrayBlockingQueue q = populatedQueue(SIZE);
378 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
379 >        Thread t = newStartedThread(new CheckedRunnable() {
380              public void realRun() throws InterruptedException {
399                ArrayBlockingQueue q = populatedQueue(SIZE);
381                  for (int i = 0; i < SIZE; ++i) {
382 <                    threadAssertEquals(i, ((Integer)q.take()).intValue());
382 >                    assertEquals(i, q.take());
383                  }
403                q.take();
404            }};
384  
385 <        t.start();
386 <            Thread.sleep(SHORT_DELAY_MS);
387 <            t.interrupt();
388 <            t.join();
389 <    }
385 >                Thread.currentThread().interrupt();
386 >                try {
387 >                    q.take();
388 >                    shouldThrow();
389 >                } catch (InterruptedException success) {}
390 >                assertFalse(Thread.interrupted());
391  
392 +                pleaseInterrupt.countDown();
393 +                try {
394 +                    q.take();
395 +                    shouldThrow();
396 +                } catch (InterruptedException success) {}
397 +                assertFalse(Thread.interrupted());
398 +            }});
399 +
400 +        await(pleaseInterrupt);
401 +        assertThreadStaysAlive(t);
402 +        t.interrupt();
403 +        awaitTermination(t);
404 +    }
405  
406      /**
407       * poll succeeds unless empty
# Line 416 | Line 409 | public class ArrayBlockingQueueTest exte
409      public void testPoll() {
410          ArrayBlockingQueue q = populatedQueue(SIZE);
411          for (int i = 0; i < SIZE; ++i) {
412 <            assertEquals(i, ((Integer)q.poll()).intValue());
412 >            assertEquals(i, q.poll());
413          }
414          assertNull(q.poll());
415      }
416  
417      /**
418 <     * timed pool with zero timeout succeeds when non-empty, else times out
418 >     * timed poll with zero timeout succeeds when non-empty, else times out
419       */
420      public void testTimedPoll0() throws InterruptedException {
421          ArrayBlockingQueue q = populatedQueue(SIZE);
422          for (int i = 0; i < SIZE; ++i) {
423 <            assertEquals(i, ((Integer)q.poll(0, MILLISECONDS)).intValue());
423 >            assertEquals(i, q.poll(0, MILLISECONDS));
424          }
425          assertNull(q.poll(0, MILLISECONDS));
426 +        checkEmpty(q);
427      }
428  
429      /**
430 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
430 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
431       */
432      public void testTimedPoll() throws InterruptedException {
433          ArrayBlockingQueue q = populatedQueue(SIZE);
434          for (int i = 0; i < SIZE; ++i) {
435 <            assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, MILLISECONDS)).intValue());
436 <        }
437 <        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
435 >            long startTime = System.nanoTime();
436 >            assertEquals(i, q.poll(LONG_DELAY_MS, MILLISECONDS));
437 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
438 >        }
439 >        long startTime = System.nanoTime();
440 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
441 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
442 >        checkEmpty(q);
443      }
444  
445      /**
# Line 448 | Line 447 | public class ArrayBlockingQueueTest exte
447       * returning timeout status
448       */
449      public void testInterruptedTimedPoll() throws InterruptedException {
450 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
450 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
451 >        final CountDownLatch aboutToWait = new CountDownLatch(1);
452 >        Thread t = newStartedThread(new CheckedRunnable() {
453              public void realRun() throws InterruptedException {
453                ArrayBlockingQueue q = populatedQueue(SIZE);
454                  for (int i = 0; i < SIZE; ++i) {
455 <                    threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, MILLISECONDS)).intValue());
455 >                    long t0 = System.nanoTime();
456 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
457 >                    assertTrue(millisElapsedSince(t0) < SMALL_DELAY_MS);
458                  }
459 <                q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
460 <            }};
461 <
462 <        t.start();
463 <        Thread.sleep(SMALL_DELAY_MS);
464 <        t.interrupt();
465 <        t.join();
466 <    }
467 <
466 <    /**
467 <     *  timed poll before a delayed offer fails; after offer succeeds;
468 <     *  on interruption throws
469 <     */
470 <    public void testTimedPollWithOffer() throws InterruptedException {
471 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
472 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
473 <            public void realRun() throws InterruptedException {
474 <                threadAssertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
475 <                q.poll(LONG_DELAY_MS, MILLISECONDS);
476 <                q.poll(LONG_DELAY_MS, MILLISECONDS);
477 <            }};
459 >                long t0 = System.nanoTime();
460 >                aboutToWait.countDown();
461 >                try {
462 >                    q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
463 >                    shouldThrow();
464 >                } catch (InterruptedException success) {
465 >                    assertTrue(millisElapsedSince(t0) < MEDIUM_DELAY_MS);
466 >                }
467 >            }});
468  
469 <        t.start();
470 <        Thread.sleep(SMALL_DELAY_MS);
481 <        assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
469 >        aboutToWait.await();
470 >        waitForThreadToEnterWaitState(t, SMALL_DELAY_MS);
471          t.interrupt();
472 <        t.join();
472 >        awaitTermination(t, MEDIUM_DELAY_MS);
473 >        checkEmpty(q);
474      }
475  
486
476      /**
477       * peek returns next element, or null if empty
478       */
479      public void testPeek() {
480          ArrayBlockingQueue q = populatedQueue(SIZE);
481          for (int i = 0; i < SIZE; ++i) {
482 <            assertEquals(i, ((Integer)q.peek()).intValue());
483 <            q.poll();
482 >            assertEquals(i, q.peek());
483 >            assertEquals(i, q.poll());
484              assertTrue(q.peek() == null ||
485 <                       i != ((Integer)q.peek()).intValue());
485 >                       !q.peek().equals(i));
486          }
487          assertNull(q.peek());
488      }
# Line 504 | Line 493 | public class ArrayBlockingQueueTest exte
493      public void testElement() {
494          ArrayBlockingQueue q = populatedQueue(SIZE);
495          for (int i = 0; i < SIZE; ++i) {
496 <            assertEquals(i, ((Integer)q.element()).intValue());
497 <            q.poll();
496 >            assertEquals(i, q.element());
497 >            assertEquals(i, q.poll());
498          }
499          try {
500              q.element();
# Line 519 | Line 508 | public class ArrayBlockingQueueTest exte
508      public void testRemove() {
509          ArrayBlockingQueue q = populatedQueue(SIZE);
510          for (int i = 0; i < SIZE; ++i) {
511 <            assertEquals(i, ((Integer)q.remove()).intValue());
511 >            assertEquals(i, q.remove());
512          }
513          try {
514              q.remove();
# Line 528 | Line 517 | public class ArrayBlockingQueueTest exte
517      }
518  
519      /**
531     * remove(x) removes x and returns true if present
532     */
533    public void testRemoveElement() {
534        ArrayBlockingQueue q = populatedQueue(SIZE);
535        for (int i = 1; i < SIZE; i+=2) {
536            assertTrue(q.remove(new Integer(i)));
537        }
538        for (int i = 0; i < SIZE; i+=2) {
539            assertTrue(q.remove(new Integer(i)));
540            assertFalse(q.remove(new Integer(i+1)));
541        }
542        assertTrue(q.isEmpty());
543    }
544
545    /**
520       * contains(x) reports true when elements added but not yet removed
521       */
522      public void testContains() {
523          ArrayBlockingQueue q = populatedQueue(SIZE);
524          for (int i = 0; i < SIZE; ++i) {
525              assertTrue(q.contains(new Integer(i)));
526 <            q.poll();
526 >            assertEquals(i, q.poll());
527              assertFalse(q.contains(new Integer(i)));
528          }
529      }
# Line 619 | Line 593 | public class ArrayBlockingQueueTest exte
593          }
594      }
595  
596 <    /**
597 <     *  toArray contains all elements
624 <     */
625 <    public void testToArray() throws InterruptedException {
626 <        ArrayBlockingQueue q = populatedQueue(SIZE);
596 >    void checkToArray(ArrayBlockingQueue q) {
597 >        int size = q.size();
598          Object[] o = q.toArray();
599 <        for (int i = 0; i < o.length; i++)
600 <            assertEquals(o[i], q.take());
599 >        assertEquals(size, o.length);
600 >        Iterator it = q.iterator();
601 >        for (int i = 0; i < size; i++) {
602 >            Integer x = (Integer) it.next();
603 >            assertEquals((Integer)o[0] + i, (int) x);
604 >            assertSame(o[i], x);
605 >        }
606      }
607  
608      /**
609 <     * toArray(a) contains all elements
609 >     * toArray() contains all elements in FIFO order
610       */
611 <    public void testToArray2() throws InterruptedException {
612 <        ArrayBlockingQueue q = populatedQueue(SIZE);
613 <        Integer[] ints = new Integer[SIZE];
614 <        ints = (Integer[])q.toArray(ints);
615 <        for (int i = 0; i < ints.length; i++)
616 <            assertEquals(ints[i], q.take());
611 >    public void testToArray() {
612 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
613 >        for (int i = 0; i < SIZE; i++) {
614 >            checkToArray(q);
615 >            q.add(i);
616 >        }
617 >        // Provoke wraparound
618 >        for (int i = 0; i < SIZE; i++) {
619 >            checkToArray(q);
620 >            assertEquals(i, q.poll());
621 >            checkToArray(q);
622 >            q.add(SIZE+i);
623 >        }
624 >        for (int i = 0; i < SIZE; i++) {
625 >            checkToArray(q);
626 >            assertEquals(SIZE+i, q.poll());
627 >        }
628 >    }
629 >
630 >    void checkToArray2(ArrayBlockingQueue q) {
631 >        int size = q.size();
632 >        Integer[] a1 = size == 0 ? null : new Integer[size-1];
633 >        Integer[] a2 = new Integer[size];
634 >        Integer[] a3 = new Integer[size+2];
635 >        if (size > 0) Arrays.fill(a1, 42);
636 >        Arrays.fill(a2, 42);
637 >        Arrays.fill(a3, 42);
638 >        Integer[] b1 = size == 0 ? null : (Integer[]) q.toArray(a1);
639 >        Integer[] b2 = (Integer[]) q.toArray(a2);
640 >        Integer[] b3 = (Integer[]) q.toArray(a3);
641 >        assertSame(a2, b2);
642 >        assertSame(a3, b3);
643 >        Iterator it = q.iterator();
644 >        for (int i = 0; i < size; i++) {
645 >            Integer x = (Integer) it.next();
646 >            assertSame(b1[i], x);
647 >            assertEquals(b1[0] + i, (int) x);
648 >            assertSame(b2[i], x);
649 >            assertSame(b3[i], x);
650 >        }
651 >        assertNull(a3[size]);
652 >        assertEquals(42, (int) a3[size+1]);
653 >        if (size > 0) {
654 >            assertNotSame(a1, b1);
655 >            assertEquals(size, b1.length);
656 >            for (int i = 0; i < a1.length; i++) {
657 >                assertEquals(42, (int) a1[i]);
658 >            }
659 >        }
660      }
661  
662      /**
663 <     * toArray(null) throws NPE
663 >     * toArray(a) contains all elements in FIFO order
664       */
665 <    public void testToArray_BadArg() {
666 <        try {
667 <            ArrayBlockingQueue q = populatedQueue(SIZE);
668 <            Object o[] = q.toArray(null);
669 <            shouldThrow();
670 <        } catch (NullPointerException success) {}
665 >    public void testToArray2() {
666 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
667 >        for (int i = 0; i < SIZE; i++) {
668 >            checkToArray2(q);
669 >            q.add(i);
670 >        }
671 >        // Provoke wraparound
672 >        for (int i = 0; i < SIZE; i++) {
673 >            checkToArray2(q);
674 >            assertEquals(i, q.poll());
675 >            checkToArray2(q);
676 >            q.add(SIZE+i);
677 >        }
678 >        for (int i = 0; i < SIZE; i++) {
679 >            checkToArray2(q);
680 >            assertEquals(SIZE+i, q.poll());
681 >        }
682      }
683  
684      /**
685 <     * toArray with incompatible array type throws CCE
685 >     * toArray(incompatible array type) throws ArrayStoreException
686       */
687      public void testToArray1_BadArg() {
688 +        ArrayBlockingQueue q = populatedQueue(SIZE);
689          try {
690 <            ArrayBlockingQueue q = populatedQueue(SIZE);
660 <            Object o[] = q.toArray(new String[10] );
690 >            q.toArray(new String[10]);
691              shouldThrow();
692          } catch (ArrayStoreException success) {}
693      }
694  
665
695      /**
696       * iterator iterates through all elements
697       */
# Line 677 | Line 706 | public class ArrayBlockingQueueTest exte
706      /**
707       * iterator.remove removes current element
708       */
709 <    public void testIteratorRemove () {
709 >    public void testIteratorRemove() {
710          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
711          q.add(two);
712          q.add(one);
# Line 688 | Line 717 | public class ArrayBlockingQueueTest exte
717          it.remove();
718  
719          it = q.iterator();
720 <        assertEquals(it.next(), one);
721 <        assertEquals(it.next(), three);
720 >        assertSame(it.next(), one);
721 >        assertSame(it.next(), three);
722          assertFalse(it.hasNext());
723      }
724  
# Line 706 | Line 735 | public class ArrayBlockingQueueTest exte
735  
736          int k = 0;
737          for (Iterator it = q.iterator(); it.hasNext();) {
738 <            int i = ((Integer)(it.next())).intValue();
710 <            assertEquals(++k, i);
738 >            assertEquals(++k, it.next());
739          }
740          assertEquals(3, k);
741      }
# Line 715 | Line 743 | public class ArrayBlockingQueueTest exte
743      /**
744       * Modifications do not cause iterators to fail
745       */
746 <    public void testWeaklyConsistentIteration () {
746 >    public void testWeaklyConsistentIteration() {
747          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
748          q.add(one);
749          q.add(two);
# Line 727 | Line 755 | public class ArrayBlockingQueueTest exte
755          assertEquals(0, q.size());
756      }
757  
730
758      /**
759       * toString contains toStrings of elements
760       */
# Line 735 | Line 762 | public class ArrayBlockingQueueTest exte
762          ArrayBlockingQueue q = populatedQueue(SIZE);
763          String s = q.toString();
764          for (int i = 0; i < SIZE; ++i) {
765 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
765 >            assertTrue(s.contains(String.valueOf(i)));
766          }
767      }
768  
742
769      /**
770       * offer transfers elements across Executor tasks
771       */
# Line 748 | Line 774 | public class ArrayBlockingQueueTest exte
774          q.add(one);
775          q.add(two);
776          ExecutorService executor = Executors.newFixedThreadPool(2);
777 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
778          executor.execute(new CheckedRunnable() {
779              public void realRun() throws InterruptedException {
780 <                threadAssertFalse(q.offer(three));
781 <                threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
782 <                threadAssertEquals(0, q.remainingCapacity());
780 >                assertFalse(q.offer(three));
781 >                threadsStarted.await();
782 >                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
783 >                assertEquals(0, q.remainingCapacity());
784              }});
785  
786          executor.execute(new CheckedRunnable() {
787              public void realRun() throws InterruptedException {
788 <                Thread.sleep(SMALL_DELAY_MS);
789 <                threadAssertEquals(one, q.take());
788 >                threadsStarted.await();
789 >                assertEquals(0, q.remainingCapacity());
790 >                assertSame(one, q.take());
791              }});
792  
793          joinPool(executor);
765
794      }
795  
796      /**
797 <     * poll retrieves elements across Executor threads
797 >     * timed poll retrieves elements across Executor threads
798       */
799      public void testPollInExecutor() {
800          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
801 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
802          ExecutorService executor = Executors.newFixedThreadPool(2);
803          executor.execute(new CheckedRunnable() {
804              public void realRun() throws InterruptedException {
805 <                threadAssertNull(q.poll());
806 <                threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
807 <                threadAssertTrue(q.isEmpty());
805 >                assertNull(q.poll());
806 >                threadsStarted.await();
807 >                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
808 >                checkEmpty(q);
809              }});
810  
811          executor.execute(new CheckedRunnable() {
812              public void realRun() throws InterruptedException {
813 <                Thread.sleep(SMALL_DELAY_MS);
813 >                threadsStarted.await();
814                  q.put(one);
815              }});
816  
# Line 791 | Line 821 | public class ArrayBlockingQueueTest exte
821       * A deserialized serialized queue has same elements in same order
822       */
823      public void testSerialization() throws Exception {
824 <        ArrayBlockingQueue q = populatedQueue(SIZE);
825 <
796 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
797 <        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
798 <        out.writeObject(q);
799 <        out.close();
824 >        Queue x = populatedQueue(SIZE);
825 >        Queue y = serialClone(x);
826  
827 <        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
828 <        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
829 <        ArrayBlockingQueue r = (ArrayBlockingQueue)in.readObject();
830 <        assertEquals(q.size(), r.size());
831 <        while (!q.isEmpty())
832 <            assertEquals(q.remove(), r.remove());
833 <    }
834 <
835 <    /**
810 <     * drainTo(null) throws NPE
811 <     */
812 <    public void testDrainToNull() {
813 <        ArrayBlockingQueue q = populatedQueue(SIZE);
814 <        try {
815 <            q.drainTo(null);
816 <            shouldThrow();
817 <        } catch (NullPointerException success) {}
818 <    }
819 <
820 <    /**
821 <     * drainTo(this) throws IAE
822 <     */
823 <    public void testDrainToSelf() {
824 <        ArrayBlockingQueue q = populatedQueue(SIZE);
825 <        try {
826 <            q.drainTo(q);
827 <            shouldThrow();
828 <        } catch (IllegalArgumentException success) {}
827 >        assertNotSame(x, y);
828 >        assertEquals(x.size(), y.size());
829 >        assertEquals(x.toString(), y.toString());
830 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
831 >        while (!x.isEmpty()) {
832 >            assertFalse(y.isEmpty());
833 >            assertEquals(x.remove(), y.remove());
834 >        }
835 >        assertTrue(y.isEmpty());
836      }
837  
838      /**
# Line 835 | Line 842 | public class ArrayBlockingQueueTest exte
842          ArrayBlockingQueue q = populatedQueue(SIZE);
843          ArrayList l = new ArrayList();
844          q.drainTo(l);
845 <        assertEquals(q.size(), 0);
846 <        assertEquals(l.size(), SIZE);
845 >        assertEquals(0, q.size());
846 >        assertEquals(SIZE, l.size());
847          for (int i = 0; i < SIZE; ++i)
848              assertEquals(l.get(i), new Integer(i));
849          q.add(zero);
# Line 846 | Line 853 | public class ArrayBlockingQueueTest exte
853          assertTrue(q.contains(one));
854          l.clear();
855          q.drainTo(l);
856 <        assertEquals(q.size(), 0);
857 <        assertEquals(l.size(), 2);
856 >        assertEquals(0, q.size());
857 >        assertEquals(2, l.size());
858          for (int i = 0; i < 2; ++i)
859              assertEquals(l.get(i), new Integer(i));
860      }
# Line 873 | Line 880 | public class ArrayBlockingQueueTest exte
880      }
881  
882      /**
883 <     * drainTo(null, n) throws NPE
877 <     */
878 <    public void testDrainToNullN() {
879 <        ArrayBlockingQueue 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 <        ArrayBlockingQueue q = populatedQueue(SIZE);
891 <        try {
892 <            q.drainTo(q, 0);
893 <            shouldThrow();
894 <        } catch (IllegalArgumentException success) {}
895 <    }
896 <
897 <    /**
898 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
883 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
884       */
885      public void testDrainToN() {
886          ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE*2);
# Line 904 | Line 889 | public class ArrayBlockingQueueTest exte
889                  assertTrue(q.offer(new Integer(j)));
890              ArrayList l = new ArrayList();
891              q.drainTo(l, i);
892 <            int k = (i < SIZE)? i : SIZE;
893 <            assertEquals(l.size(), k);
894 <            assertEquals(q.size(), SIZE-k);
892 >            int k = (i < SIZE) ? i : SIZE;
893 >            assertEquals(k, l.size());
894 >            assertEquals(SIZE-k, q.size());
895              for (int j = 0; j < k; ++j)
896                  assertEquals(l.get(j), new Integer(j));
897 <            while (q.poll() != null) ;
897 >            do {} while (q.poll() != null);
898          }
899      }
900  
901 +    /**
902 +     * remove(null), contains(null) always return false
903 +     */
904 +    public void testNeverContainsNull() {
905 +        Collection<?>[] qs = {
906 +            new ArrayBlockingQueue<Object>(10),
907 +            populatedQueue(2),
908 +        };
909 +
910 +        for (Collection<?> q : qs) {
911 +            assertFalse(q.contains(null));
912 +            assertFalse(q.remove(null));
913 +        }
914 +    }
915   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines