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.23 by jsr166, Sat Nov 21 21:00:34 2009 UTC vs.
Revision 1.71 by jsr166, Sat Aug 6 17:02:49 2016 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9
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 >        main(suite(), args);
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, elements);
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 131 | Line 159 | public class ArrayBlockingQueueTest exte
159       * remainingCapacity decreases on add, increases on remove
160       */
161      public void testRemainingCapacity() {
162 <        ArrayBlockingQueue q = populatedQueue(SIZE);
162 >        BlockingQueue q = populatedQueue(SIZE);
163          for (int i = 0; i < SIZE; ++i) {
164              assertEquals(i, q.remainingCapacity());
165 <            assertEquals(SIZE-i, q.size());
166 <            q.remove();
165 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
166 >            assertEquals(i, q.remove());
167          }
168          for (int i = 0; i < SIZE; ++i) {
169 <            assertEquals(SIZE-i, q.remainingCapacity());
170 <            assertEquals(i, q.size());
171 <            q.add(new Integer(i));
169 >            assertEquals(SIZE - i, q.remainingCapacity());
170 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
171 >            assertTrue(q.add(i));
172          }
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 179 | Line 185 | public class ArrayBlockingQueueTest exte
185       * add succeeds if not full; throws ISE if full
186       */
187      public void testAdd() {
188 +        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
189 +        for (int i = 0; i < SIZE; ++i) {
190 +            assertTrue(q.add(new Integer(i)));
191 +        }
192 +        assertEquals(0, q.remainingCapacity());
193          try {
183            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
184            for (int i = 0; i < SIZE; ++i) {
185                assertTrue(q.add(new Integer(i)));
186            }
187            assertEquals(0, q.remainingCapacity());
194              q.add(new Integer(SIZE));
195              shouldThrow();
196          } catch (IllegalStateException success) {}
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() {
203 +        ArrayBlockingQueue q = populatedQueue(SIZE);
204          try {
209            ArrayBlockingQueue q = populatedQueue(SIZE);
205              q.addAll(q);
206              shouldThrow();
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
213       */
214      public void testAddAll3() {
215 +        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
216 +        Integer[] ints = new Integer[SIZE];
217 +        for (int i = 0; i < SIZE - 1; ++i)
218 +            ints[i] = new Integer(i);
219          try {
233            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
234            Integer[] ints = new Integer[SIZE];
235            for (int i = 0; i < SIZE-1; ++i)
236                ints[i] = new Integer(i);
220              q.addAll(Arrays.asList(ints));
221              shouldThrow();
222          } catch (NullPointerException success) {}
223      }
224 +
225      /**
226       * addAll throws ISE if not enough room
227       */
228      public void testAddAll4() {
229 +        ArrayBlockingQueue q = new ArrayBlockingQueue(1);
230 +        Integer[] ints = new Integer[SIZE];
231 +        for (int i = 0; i < SIZE; ++i)
232 +            ints[i] = new Integer(i);
233          try {
246            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
247            Integer[] ints = new Integer[SIZE];
248            for (int i = 0; i < SIZE; ++i)
249                ints[i] = new Integer(i);
234              q.addAll(Arrays.asList(ints));
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 {
258          ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
259          for (int i = 0; i < SIZE; ++i) {
260 <            Integer I = new Integer(i);
261 <            q.put(I);
262 <            assertTrue(q.contains(I));
260 >            Integer x = new Integer(i);
261 >            q.put(x);
262 >            assertTrue(q.contains(x));
263          }
264          assertEquals(0, q.remainingCapacity());
265      }
# 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 success) {
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 success) {
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 Thread(new CheckedRunnable() {
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 {
454 <                ArrayBlockingQueue q = populatedQueue(SIZE);
454 >                long startTime = System.nanoTime();
455                  for (int i = 0; i < SIZE; ++i) {
456 <                    assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, MILLISECONDS)).intValue());
456 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
457                  }
458 <                try {
458 <                    q.poll(SMALL_DELAY_MS, MILLISECONDS);
459 <                    shouldThrow();
460 <                } catch (InterruptedException success) {}
461 <            }});
462 <
463 <        t.start();
464 <        Thread.sleep(SHORT_DELAY_MS);
465 <        t.interrupt();
466 <        t.join();
467 <    }
468 <
469 <    /**
470 <     *  timed poll before a delayed offer fails; after offer succeeds;
471 <     *  on interruption throws
472 <     */
473 <    public void testTimedPollWithOffer() throws InterruptedException {
474 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
475 <        Thread t = new Thread(new CheckedRunnable() {
476 <            public void realRun() throws InterruptedException {
477 <                assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
478 <                assertSame(zero, q.poll(LONG_DELAY_MS, MILLISECONDS));
458 >                aboutToWait.countDown();
459                  try {
460                      q.poll(LONG_DELAY_MS, MILLISECONDS);
461                      shouldThrow();
462 <                } catch (InterruptedException success) {}
462 >                } catch (InterruptedException success) {
463 >                    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
464 >                }
465              }});
466  
467 <        t.start();
468 <        Thread.sleep(SMALL_DELAY_MS);
487 <        assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
467 >        await(aboutToWait);
468 >        waitForThreadToEnterWaitState(t);
469          t.interrupt();
470 <        t.join();
470 >        awaitTermination(t);
471 >        checkEmpty(q);
472      }
473  
492
474      /**
475       * peek returns next element, or null if empty
476       */
477      public void testPeek() {
478          ArrayBlockingQueue q = populatedQueue(SIZE);
479          for (int i = 0; i < SIZE; ++i) {
480 <            assertEquals(i, ((Integer)q.peek()).intValue());
481 <            q.poll();
480 >            assertEquals(i, q.peek());
481 >            assertEquals(i, q.poll());
482              assertTrue(q.peek() == null ||
483 <                       i != ((Integer)q.peek()).intValue());
483 >                       !q.peek().equals(i));
484          }
485          assertNull(q.peek());
486      }
# Line 510 | Line 491 | public class ArrayBlockingQueueTest exte
491      public void testElement() {
492          ArrayBlockingQueue q = populatedQueue(SIZE);
493          for (int i = 0; i < SIZE; ++i) {
494 <            assertEquals(i, ((Integer)q.element()).intValue());
495 <            q.poll();
494 >            assertEquals(i, q.element());
495 >            assertEquals(i, q.poll());
496          }
497          try {
498              q.element();
# Line 525 | Line 506 | public class ArrayBlockingQueueTest exte
506      public void testRemove() {
507          ArrayBlockingQueue q = populatedQueue(SIZE);
508          for (int i = 0; i < SIZE; ++i) {
509 <            assertEquals(i, ((Integer)q.remove()).intValue());
509 >            assertEquals(i, q.remove());
510          }
511          try {
512              q.remove();
# Line 534 | Line 515 | public class ArrayBlockingQueueTest exte
515      }
516  
517      /**
537     * remove(x) removes x and returns true if present
538     */
539    public void testRemoveElement() {
540        ArrayBlockingQueue q = populatedQueue(SIZE);
541        for (int i = 1; i < SIZE; i+=2) {
542            assertTrue(q.remove(new Integer(i)));
543        }
544        for (int i = 0; i < SIZE; i+=2) {
545            assertTrue(q.remove(new Integer(i)));
546            assertFalse(q.remove(new Integer(i+1)));
547        }
548        assertTrue(q.isEmpty());
549    }
550
551    /**
518       * contains(x) reports true when elements added but not yet removed
519       */
520      public void testContains() {
521          ArrayBlockingQueue q = populatedQueue(SIZE);
522          for (int i = 0; i < SIZE; ++i) {
523              assertTrue(q.contains(new Integer(i)));
524 <            q.poll();
524 >            assertEquals(i, q.poll());
525              assertFalse(q.contains(new Integer(i)));
526          }
527      }
# Line 604 | Line 570 | public class ArrayBlockingQueueTest exte
570                  assertTrue(changed);
571  
572              assertTrue(q.containsAll(p));
573 <            assertEquals(SIZE-i, q.size());
573 >            assertEquals(SIZE - i, q.size());
574              p.remove();
575          }
576      }
# Line 617 | Line 583 | public class ArrayBlockingQueueTest exte
583              ArrayBlockingQueue q = populatedQueue(SIZE);
584              ArrayBlockingQueue p = populatedQueue(i);
585              assertTrue(q.removeAll(p));
586 <            assertEquals(SIZE-i, q.size());
586 >            assertEquals(SIZE - i, q.size());
587              for (int j = 0; j < i; ++j) {
588 <                Integer I = (Integer)(p.remove());
589 <                assertFalse(q.contains(I));
588 >                Integer x = (Integer)(p.remove());
589 >                assertFalse(q.contains(x));
590              }
591          }
592      }
593  
594 <    /**
595 <     *  toArray contains all elements
630 <     */
631 <    public void testToArray() throws InterruptedException {
632 <        ArrayBlockingQueue q = populatedQueue(SIZE);
594 >    void checkToArray(ArrayBlockingQueue q) {
595 >        int size = q.size();
596          Object[] o = q.toArray();
597 <        for (int i = 0; i < o.length; i++)
598 <            assertEquals(o[i], q.take());
597 >        assertEquals(size, o.length);
598 >        Iterator it = q.iterator();
599 >        for (int i = 0; i < size; i++) {
600 >            Integer x = (Integer) it.next();
601 >            assertEquals((Integer)o[0] + i, (int) x);
602 >            assertSame(o[i], x);
603 >        }
604      }
605  
606      /**
607 <     * toArray(a) contains all elements
607 >     * toArray() contains all elements in FIFO order
608       */
609 <    public void testToArray2() throws InterruptedException {
610 <        ArrayBlockingQueue q = populatedQueue(SIZE);
611 <        Integer[] ints = new Integer[SIZE];
612 <        ints = (Integer[])q.toArray(ints);
613 <        for (int i = 0; i < ints.length; i++)
614 <            assertEquals(ints[i], q.take());
609 >    public void testToArray() {
610 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
611 >        for (int i = 0; i < SIZE; i++) {
612 >            checkToArray(q);
613 >            q.add(i);
614 >        }
615 >        // Provoke wraparound
616 >        for (int i = 0; i < SIZE; i++) {
617 >            checkToArray(q);
618 >            assertEquals(i, q.poll());
619 >            checkToArray(q);
620 >            q.add(SIZE + i);
621 >        }
622 >        for (int i = 0; i < SIZE; i++) {
623 >            checkToArray(q);
624 >            assertEquals(SIZE + i, q.poll());
625 >        }
626 >    }
627 >
628 >    void checkToArray2(ArrayBlockingQueue q) {
629 >        int size = q.size();
630 >        Integer[] a1 = (size == 0) ? null : new Integer[size - 1];
631 >        Integer[] a2 = new Integer[size];
632 >        Integer[] a3 = new Integer[size + 2];
633 >        if (size > 0) Arrays.fill(a1, 42);
634 >        Arrays.fill(a2, 42);
635 >        Arrays.fill(a3, 42);
636 >        Integer[] b1 = (size == 0) ? null : (Integer[]) q.toArray(a1);
637 >        Integer[] b2 = (Integer[]) q.toArray(a2);
638 >        Integer[] b3 = (Integer[]) q.toArray(a3);
639 >        assertSame(a2, b2);
640 >        assertSame(a3, b3);
641 >        Iterator it = q.iterator();
642 >        for (int i = 0; i < size; i++) {
643 >            Integer x = (Integer) it.next();
644 >            assertSame(b1[i], x);
645 >            assertEquals(b1[0] + i, (int) x);
646 >            assertSame(b2[i], x);
647 >            assertSame(b3[i], x);
648 >        }
649 >        assertNull(a3[size]);
650 >        assertEquals(42, (int) a3[size + 1]);
651 >        if (size > 0) {
652 >            assertNotSame(a1, b1);
653 >            assertEquals(size, b1.length);
654 >            for (int i = 0; i < a1.length; i++) {
655 >                assertEquals(42, (int) a1[i]);
656 >            }
657 >        }
658      }
659  
660      /**
661 <     * toArray(null) throws NPE
661 >     * toArray(a) contains all elements in FIFO order
662       */
663 <    public void testToArray_BadArg() {
664 <        try {
665 <            ArrayBlockingQueue q = populatedQueue(SIZE);
666 <            Object o[] = q.toArray(null);
667 <            shouldThrow();
668 <        } catch (NullPointerException success) {}
663 >    public void testToArray2() {
664 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
665 >        for (int i = 0; i < SIZE; i++) {
666 >            checkToArray2(q);
667 >            q.add(i);
668 >        }
669 >        // Provoke wraparound
670 >        for (int i = 0; i < SIZE; i++) {
671 >            checkToArray2(q);
672 >            assertEquals(i, q.poll());
673 >            checkToArray2(q);
674 >            q.add(SIZE + i);
675 >        }
676 >        for (int i = 0; i < SIZE; i++) {
677 >            checkToArray2(q);
678 >            assertEquals(SIZE + i, q.poll());
679 >        }
680      }
681  
682      /**
683 <     * toArray with incompatible array type throws CCE
683 >     * toArray(incompatible array type) throws ArrayStoreException
684       */
685      public void testToArray1_BadArg() {
686 +        ArrayBlockingQueue q = populatedQueue(SIZE);
687          try {
688 <            ArrayBlockingQueue q = populatedQueue(SIZE);
666 <            Object o[] = q.toArray(new String[10] );
688 >            q.toArray(new String[10]);
689              shouldThrow();
690          } catch (ArrayStoreException success) {}
691      }
692  
671
693      /**
694       * iterator iterates through all elements
695       */
696      public void testIterator() throws InterruptedException {
697          ArrayBlockingQueue q = populatedQueue(SIZE);
698          Iterator it = q.iterator();
699 <        while (it.hasNext()) {
699 >        int i;
700 >        for (i = 0; it.hasNext(); i++)
701 >            assertTrue(q.contains(it.next()));
702 >        assertEquals(i, SIZE);
703 >        assertIteratorExhausted(it);
704 >
705 >        it = q.iterator();
706 >        for (i = 0; it.hasNext(); i++)
707              assertEquals(it.next(), q.take());
708 <        }
708 >        assertEquals(i, SIZE);
709 >        assertIteratorExhausted(it);
710 >    }
711 >
712 >    /**
713 >     * iterator of empty collection has no elements
714 >     */
715 >    public void testEmptyIterator() {
716 >        assertIteratorExhausted(new ArrayBlockingQueue(SIZE).iterator());
717      }
718  
719      /**
720       * iterator.remove removes current element
721       */
722 <    public void testIteratorRemove () {
722 >    public void testIteratorRemove() {
723          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
724          q.add(two);
725          q.add(one);
# Line 694 | Line 730 | public class ArrayBlockingQueueTest exte
730          it.remove();
731  
732          it = q.iterator();
733 <        assertEquals(it.next(), one);
734 <        assertEquals(it.next(), three);
733 >        assertSame(it.next(), one);
734 >        assertSame(it.next(), three);
735          assertFalse(it.hasNext());
736      }
737  
# Line 712 | Line 748 | public class ArrayBlockingQueueTest exte
748  
749          int k = 0;
750          for (Iterator it = q.iterator(); it.hasNext();) {
751 <            int i = ((Integer)(it.next())).intValue();
716 <            assertEquals(++k, i);
751 >            assertEquals(++k, it.next());
752          }
753          assertEquals(3, k);
754      }
# Line 721 | Line 756 | public class ArrayBlockingQueueTest exte
756      /**
757       * Modifications do not cause iterators to fail
758       */
759 <    public void testWeaklyConsistentIteration () {
759 >    public void testWeaklyConsistentIteration() {
760          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
761          q.add(one);
762          q.add(two);
# Line 733 | Line 768 | public class ArrayBlockingQueueTest exte
768          assertEquals(0, q.size());
769      }
770  
736
771      /**
772       * toString contains toStrings of elements
773       */
# Line 741 | Line 775 | public class ArrayBlockingQueueTest exte
775          ArrayBlockingQueue q = populatedQueue(SIZE);
776          String s = q.toString();
777          for (int i = 0; i < SIZE; ++i) {
778 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
778 >            assertTrue(s.contains(String.valueOf(i)));
779          }
780      }
781  
748
782      /**
783       * offer transfers elements across Executor tasks
784       */
# Line 753 | Line 786 | public class ArrayBlockingQueueTest exte
786          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
787          q.add(one);
788          q.add(two);
789 <        ExecutorService executor = Executors.newFixedThreadPool(2);
790 <        executor.execute(new CheckedRunnable() {
791 <            public void realRun() throws InterruptedException {
792 <                threadAssertFalse(q.offer(three));
793 <                threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
794 <                threadAssertEquals(0, q.remainingCapacity());
795 <            }});
796 <
797 <        executor.execute(new CheckedRunnable() {
798 <            public void realRun() throws InterruptedException {
799 <                Thread.sleep(SMALL_DELAY_MS);
800 <                threadAssertEquals(one, q.take());
801 <            }});
802 <
803 <        joinPool(executor);
804 <
789 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
790 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
791 >        try (PoolCleaner cleaner = cleaner(executor)) {
792 >            executor.execute(new CheckedRunnable() {
793 >                public void realRun() throws InterruptedException {
794 >                    assertFalse(q.offer(three));
795 >                    threadsStarted.await();
796 >                    assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
797 >                    assertEquals(0, q.remainingCapacity());
798 >                }});
799 >
800 >            executor.execute(new CheckedRunnable() {
801 >                public void realRun() throws InterruptedException {
802 >                    threadsStarted.await();
803 >                    assertEquals(0, q.remainingCapacity());
804 >                    assertSame(one, q.take());
805 >                }});
806 >        }
807      }
808  
809      /**
810 <     * poll retrieves elements across Executor threads
810 >     * timed poll retrieves elements across Executor threads
811       */
812      public void testPollInExecutor() {
813          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
814 <        ExecutorService executor = Executors.newFixedThreadPool(2);
815 <        executor.execute(new CheckedRunnable() {
816 <            public void realRun() throws InterruptedException {
817 <                threadAssertNull(q.poll());
818 <                threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
819 <                threadAssertTrue(q.isEmpty());
820 <            }});
821 <
822 <        executor.execute(new CheckedRunnable() {
823 <            public void realRun() throws InterruptedException {
824 <                Thread.sleep(SMALL_DELAY_MS);
825 <                q.put(one);
826 <            }});
827 <
828 <        joinPool(executor);
814 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
815 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
816 >        try (PoolCleaner cleaner = cleaner(executor)) {
817 >            executor.execute(new CheckedRunnable() {
818 >                public void realRun() throws InterruptedException {
819 >                    assertNull(q.poll());
820 >                    threadsStarted.await();
821 >                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
822 >                    checkEmpty(q);
823 >                }});
824 >
825 >            executor.execute(new CheckedRunnable() {
826 >                public void realRun() throws InterruptedException {
827 >                    threadsStarted.await();
828 >                    q.put(one);
829 >                }});
830 >        }
831      }
832  
833      /**
834       * A deserialized serialized queue has same elements in same order
835       */
836      public void testSerialization() throws Exception {
837 <        ArrayBlockingQueue q = populatedQueue(SIZE);
838 <
802 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
803 <        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
804 <        out.writeObject(q);
805 <        out.close();
806 <
807 <        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
808 <        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
809 <        ArrayBlockingQueue r = (ArrayBlockingQueue)in.readObject();
810 <        assertEquals(q.size(), r.size());
811 <        while (!q.isEmpty())
812 <            assertEquals(q.remove(), r.remove());
813 <    }
814 <
815 <    /**
816 <     * drainTo(null) throws NPE
817 <     */
818 <    public void testDrainToNull() {
819 <        ArrayBlockingQueue q = populatedQueue(SIZE);
820 <        try {
821 <            q.drainTo(null);
822 <            shouldThrow();
823 <        } catch (NullPointerException success) {}
824 <    }
837 >        Queue x = populatedQueue(SIZE);
838 >        Queue y = serialClone(x);
839  
840 <    /**
841 <     * drainTo(this) throws IAE
842 <     */
843 <    public void testDrainToSelf() {
844 <        ArrayBlockingQueue q = populatedQueue(SIZE);
845 <        try {
846 <            q.drainTo(q);
847 <            shouldThrow();
848 <        } catch (IllegalArgumentException success) {}
840 >        assertNotSame(x, y);
841 >        assertEquals(x.size(), y.size());
842 >        assertEquals(x.toString(), y.toString());
843 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
844 >        while (!x.isEmpty()) {
845 >            assertFalse(y.isEmpty());
846 >            assertEquals(x.remove(), y.remove());
847 >        }
848 >        assertTrue(y.isEmpty());
849      }
850  
851      /**
# Line 841 | Line 855 | public class ArrayBlockingQueueTest exte
855          ArrayBlockingQueue q = populatedQueue(SIZE);
856          ArrayList l = new ArrayList();
857          q.drainTo(l);
858 <        assertEquals(q.size(), 0);
859 <        assertEquals(l.size(), SIZE);
858 >        assertEquals(0, q.size());
859 >        assertEquals(SIZE, l.size());
860          for (int i = 0; i < SIZE; ++i)
861              assertEquals(l.get(i), new Integer(i));
862          q.add(zero);
# Line 852 | Line 866 | public class ArrayBlockingQueueTest exte
866          assertTrue(q.contains(one));
867          l.clear();
868          q.drainTo(l);
869 <        assertEquals(q.size(), 0);
870 <        assertEquals(l.size(), 2);
869 >        assertEquals(0, q.size());
870 >        assertEquals(2, l.size());
871          for (int i = 0; i < 2; ++i)
872              assertEquals(l.get(i), new Integer(i));
873      }
# Line 865 | Line 879 | public class ArrayBlockingQueueTest exte
879          final ArrayBlockingQueue q = populatedQueue(SIZE);
880          Thread t = new Thread(new CheckedRunnable() {
881              public void realRun() throws InterruptedException {
882 <                q.put(new Integer(SIZE+1));
882 >                q.put(new Integer(SIZE + 1));
883              }});
884  
885          t.start();
# Line 879 | Line 893 | public class ArrayBlockingQueueTest exte
893      }
894  
895      /**
896 <     * drainTo(null, n) throws NPE
883 <     */
884 <    public void testDrainToNullN() {
885 <        ArrayBlockingQueue q = populatedQueue(SIZE);
886 <        try {
887 <            q.drainTo(null, 0);
888 <            shouldThrow();
889 <        } catch (NullPointerException success) {}
890 <    }
891 <
892 <    /**
893 <     * drainTo(this, n) throws IAE
894 <     */
895 <    public void testDrainToSelfN() {
896 <        ArrayBlockingQueue q = populatedQueue(SIZE);
897 <        try {
898 <            q.drainTo(q, 0);
899 <            shouldThrow();
900 <        } catch (IllegalArgumentException success) {}
901 <    }
902 <
903 <    /**
904 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
896 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
897       */
898      public void testDrainToN() {
899 <        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE*2);
899 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE * 2);
900          for (int i = 0; i < SIZE + 2; ++i) {
901              for (int j = 0; j < SIZE; j++)
902                  assertTrue(q.offer(new Integer(j)));
903              ArrayList l = new ArrayList();
904              q.drainTo(l, i);
905 <            int k = (i < SIZE)? i : SIZE;
906 <            assertEquals(l.size(), k);
907 <            assertEquals(q.size(), SIZE-k);
905 >            int k = (i < SIZE) ? i : SIZE;
906 >            assertEquals(k, l.size());
907 >            assertEquals(SIZE - k, q.size());
908              for (int j = 0; j < k; ++j)
909                  assertEquals(l.get(j), new Integer(j));
910 <            while (q.poll() != null) ;
910 >            do {} while (q.poll() != null);
911          }
912      }
913  
914 +    /**
915 +     * remove(null), contains(null) always return false
916 +     */
917 +    public void testNeverContainsNull() {
918 +        Collection<?>[] qs = {
919 +            new ArrayBlockingQueue<Object>(10),
920 +            populatedQueue(2),
921 +        };
922 +
923 +        for (Collection<?> q : qs) {
924 +            assertFalse(q.contains(null));
925 +            assertFalse(q.remove(null));
926 +        }
927 +    }
928   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines