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.18 by jsr166, Sat Nov 21 10:25:05 2009 UTC vs.
Revision 1.74 by jsr166, Sun Oct 30 21:07:27 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 > import java.util.concurrent.ThreadLocalRandom;
23 >
24 > import junit.framework.Test;
25  
26   public class ArrayBlockingQueueTest extends JSR166TestCase {
27 +
28 +    public static class Fair extends BlockingQueueTest {
29 +        protected BlockingQueue emptyCollection() {
30 +            return new ArrayBlockingQueue(SIZE, true);
31 +        }
32 +    }
33 +
34 +    public static class NonFair extends BlockingQueueTest {
35 +        protected BlockingQueue emptyCollection() {
36 +            return new ArrayBlockingQueue(SIZE, false);
37 +        }
38 +    }
39 +
40      public static void main(String[] args) {
41 <        junit.textui.TestRunner.run (suite());
41 >        main(suite(), args);
42      }
43 +
44      public static Test suite() {
45 <        return new TestSuite(ArrayBlockingQueueTest.class);
45 >        class Implementation implements CollectionImplementation {
46 >            public Class<?> klazz() { return ArrayBlockingQueue.class; }
47 >            public Collection emptyCollection() { return new ArrayBlockingQueue(SIZE, false); }
48 >            public Object makeElement(int i) { return i; }
49 >            public boolean isConcurrent() { return true; }
50 >            public boolean permitsNulls() { return false; }
51 >        }
52 >        return newTestSuite(ArrayBlockingQueueTest.class,
53 >                            new Fair().testSuite(),
54 >                            new NonFair().testSuite(),
55 >                            CollectionTest.testSuite(new Implementation()));
56      }
57  
58      /**
59 <     * Create a queue of given size containing consecutive
60 <     * Integers 0 ... n.
59 >     * Returns a new queue of given size containing consecutive
60 >     * Integers 0 ... n - 1.
61       */
62 <    private ArrayBlockingQueue populatedQueue(int n) {
63 <        ArrayBlockingQueue q = new ArrayBlockingQueue(n);
62 >    private ArrayBlockingQueue<Integer> populatedQueue(int n) {
63 >        ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(n);
64          assertTrue(q.isEmpty());
65          for (int i = 0; i < n; i++)
66              assertTrue(q.offer(new Integer(i)));
67          assertFalse(q.isEmpty());
68          assertEquals(0, q.remainingCapacity());
69          assertEquals(n, q.size());
70 +        assertEquals((Integer) 0, q.peek());
71          return q;
72      }
73  
# Line 48 | Line 83 | public class ArrayBlockingQueueTest exte
83       */
84      public void testConstructor2() {
85          try {
86 <            ArrayBlockingQueue q = new ArrayBlockingQueue(0);
86 >            new ArrayBlockingQueue(0);
87              shouldThrow();
88          } catch (IllegalArgumentException success) {}
89      }
# Line 58 | Line 93 | public class ArrayBlockingQueueTest exte
93       */
94      public void testConstructor3() {
95          try {
96 <            ArrayBlockingQueue q = new ArrayBlockingQueue(1, true, null);
96 >            new ArrayBlockingQueue(1, true, null);
97              shouldThrow();
98          } catch (NullPointerException success) {}
99      }
# Line 67 | Line 102 | public class ArrayBlockingQueueTest exte
102       * Initializing from Collection of null elements throws NPE
103       */
104      public void testConstructor4() {
105 +        Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
106          try {
107 <            Integer[] ints = new Integer[SIZE];
72 <            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
107 >            new ArrayBlockingQueue(SIZE, false, elements);
108              shouldThrow();
109          } catch (NullPointerException success) {}
110      }
# Line 78 | Line 113 | public class ArrayBlockingQueueTest exte
113       * Initializing from Collection with some null elements throws NPE
114       */
115      public void testConstructor5() {
116 +        Integer[] ints = new Integer[SIZE];
117 +        for (int i = 0; i < SIZE - 1; ++i)
118 +            ints[i] = i;
119 +        Collection<Integer> elements = Arrays.asList(ints);
120          try {
121 <            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));
121 >            new ArrayBlockingQueue(SIZE, false, elements);
122              shouldThrow();
123          } catch (NullPointerException success) {}
124      }
# Line 91 | Line 127 | public class ArrayBlockingQueueTest exte
127       * Initializing from too large collection throws IAE
128       */
129      public void testConstructor6() {
130 +        Integer[] ints = new Integer[SIZE];
131 +        for (int i = 0; i < SIZE; ++i)
132 +            ints[i] = i;
133 +        Collection<Integer> elements = Arrays.asList(ints);
134          try {
135 <            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));
135 >            new ArrayBlockingQueue(SIZE - 1, false, elements);
136              shouldThrow();
137          } catch (IllegalArgumentException success) {}
138      }
# Line 104 | Line 141 | public class ArrayBlockingQueueTest exte
141       * Queue contains all elements of collection used to initialize
142       */
143      public void testConstructor7() {
144 <        try {
145 <            Integer[] ints = new Integer[SIZE];
146 <            for (int i = 0; i < SIZE; ++i)
147 <                ints[i] = new Integer(i);
148 <            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, Arrays.asList(ints));
149 <            for (int i = 0; i < SIZE; ++i)
150 <                assertEquals(ints[i], q.poll());
114 <        }
115 <        finally {}
144 >        Integer[] ints = new Integer[SIZE];
145 >        for (int i = 0; i < SIZE; ++i)
146 >            ints[i] = i;
147 >        Collection<Integer> elements = Arrays.asList(ints);
148 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, elements);
149 >        for (int i = 0; i < SIZE; ++i)
150 >            assertEquals(ints[i], q.poll());
151      }
152  
153      /**
# Line 134 | Line 169 | public class ArrayBlockingQueueTest exte
169       * remainingCapacity decreases on add, increases on remove
170       */
171      public void testRemainingCapacity() {
172 <        ArrayBlockingQueue q = populatedQueue(SIZE);
172 >        BlockingQueue q = populatedQueue(SIZE);
173          for (int i = 0; i < SIZE; ++i) {
174              assertEquals(i, q.remainingCapacity());
175 <            assertEquals(SIZE-i, q.size());
176 <            q.remove();
175 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
176 >            assertEquals(i, q.remove());
177          }
178          for (int i = 0; i < SIZE; ++i) {
179 <            assertEquals(SIZE-i, q.remainingCapacity());
180 <            assertEquals(i, q.size());
181 <            q.add(new Integer(i));
179 >            assertEquals(SIZE - i, q.remainingCapacity());
180 >            assertEquals(SIZE, q.size() + q.remainingCapacity());
181 >            assertTrue(q.add(i));
182          }
183      }
184  
185      /**
151     *  offer(null) throws NPE
152     */
153    public void testOfferNull() {
154        try {
155            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
156            q.offer(null);
157            shouldThrow();
158        } catch (NullPointerException success) {}
159    }
160
161    /**
162     *  add(null) throws NPE
163     */
164    public void testAddNull() {
165        try {
166            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
167            q.add(null);
168            shouldThrow();
169        } catch (NullPointerException success) {}
170    }
171
172    /**
186       * Offer succeeds if not full; fails if full
187       */
188      public void testOffer() {
# Line 182 | Line 195 | public class ArrayBlockingQueueTest exte
195       * add succeeds if not full; throws ISE if full
196       */
197      public void testAdd() {
198 +        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
199 +        for (int i = 0; i < SIZE; ++i) {
200 +            assertTrue(q.add(new Integer(i)));
201 +        }
202 +        assertEquals(0, q.remainingCapacity());
203          try {
186            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
187            for (int i = 0; i < SIZE; ++i) {
188                assertTrue(q.add(new Integer(i)));
189            }
190            assertEquals(0, q.remainingCapacity());
204              q.add(new Integer(SIZE));
205              shouldThrow();
206          } catch (IllegalStateException success) {}
207      }
208  
209      /**
197     *  addAll(null) throws NPE
198     */
199    public void testAddAll1() {
200        try {
201            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
202            q.addAll(null);
203            shouldThrow();
204        } catch (NullPointerException success) {}
205    }
206
207    /**
210       * addAll(this) throws IAE
211       */
212      public void testAddAllSelf() {
213 +        ArrayBlockingQueue q = populatedQueue(SIZE);
214          try {
212            ArrayBlockingQueue q = populatedQueue(SIZE);
215              q.addAll(q);
216              shouldThrow();
217          } catch (IllegalArgumentException success) {}
218      }
219  
218
219    /**
220     *  addAll of a collection with null elements throws NPE
221     */
222    public void testAddAll2() {
223        try {
224            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
225            Integer[] ints = new Integer[SIZE];
226            q.addAll(Arrays.asList(ints));
227            shouldThrow();
228        } catch (NullPointerException success) {}
229    }
220      /**
221       * addAll of a collection with any null elements throws NPE after
222       * possibly adding some elements
223       */
224      public void testAddAll3() {
225 +        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
226 +        Integer[] ints = new Integer[SIZE];
227 +        for (int i = 0; i < SIZE - 1; ++i)
228 +            ints[i] = new Integer(i);
229          try {
236            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
237            Integer[] ints = new Integer[SIZE];
238            for (int i = 0; i < SIZE-1; ++i)
239                ints[i] = new Integer(i);
230              q.addAll(Arrays.asList(ints));
231              shouldThrow();
232          } catch (NullPointerException success) {}
233      }
234 +
235      /**
236       * addAll throws ISE if not enough room
237       */
238      public void testAddAll4() {
239 +        ArrayBlockingQueue q = new ArrayBlockingQueue(1);
240 +        Integer[] ints = new Integer[SIZE];
241 +        for (int i = 0; i < SIZE; ++i)
242 +            ints[i] = new Integer(i);
243          try {
249            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
250            Integer[] ints = new Integer[SIZE];
251            for (int i = 0; i < SIZE; ++i)
252                ints[i] = new Integer(i);
244              q.addAll(Arrays.asList(ints));
245              shouldThrow();
246          } catch (IllegalStateException success) {}
247      }
248 +
249      /**
250       * Queue contains all elements, in traversal order, of successful addAll
251       */
# Line 270 | Line 262 | public class ArrayBlockingQueueTest exte
262      }
263  
264      /**
273     *  put(null) throws NPE
274     */
275    public void testPutNull() throws InterruptedException {
276        try {
277            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
278            q.put(null);
279            shouldThrow();
280        } catch (NullPointerException success) {}
281     }
282
283    /**
265       * all elements successfully put are contained
266       */
267      public void testPut() throws InterruptedException {
268          ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
269          for (int i = 0; i < SIZE; ++i) {
270 <            Integer I = new Integer(i);
271 <            q.put(I);
272 <            assertTrue(q.contains(I));
270 >            Integer x = new Integer(i);
271 >            q.put(x);
272 >            assertTrue(q.contains(x));
273          }
274          assertEquals(0, q.remainingCapacity());
275      }
# Line 298 | Line 279 | public class ArrayBlockingQueueTest exte
279       */
280      public void testBlockingPut() throws InterruptedException {
281          final ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
282 <        Thread t = new Thread(new CheckedRunnable() {
283 <            public void realRun() {
284 <                int added = 0;
282 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
283 >        Thread t = newStartedThread(new CheckedRunnable() {
284 >            public void realRun() throws InterruptedException {
285 >                for (int i = 0; i < SIZE; ++i)
286 >                    q.put(i);
287 >                assertEquals(SIZE, q.size());
288 >                assertEquals(0, q.remainingCapacity());
289 >
290 >                Thread.currentThread().interrupt();
291                  try {
292 <                    for (int i = 0; i < SIZE; ++i) {
293 <                        q.put(new Integer(i));
294 <                        ++added;
295 <                    }
309 <                    q.put(new Integer(SIZE));
310 <                    threadShouldThrow();
311 <                } catch (InterruptedException ie) {
312 <                    threadAssertEquals(added, SIZE);
313 <                }}});
292 >                    q.put(99);
293 >                    shouldThrow();
294 >                } catch (InterruptedException success) {}
295 >                assertFalse(Thread.interrupted());
296  
297 <        t.start();
298 <        Thread.sleep(MEDIUM_DELAY_MS);
297 >                pleaseInterrupt.countDown();
298 >                try {
299 >                    q.put(99);
300 >                    shouldThrow();
301 >                } catch (InterruptedException success) {}
302 >                assertFalse(Thread.interrupted());
303 >            }});
304 >
305 >        await(pleaseInterrupt);
306 >        assertThreadStaysAlive(t);
307          t.interrupt();
308 <        t.join();
308 >        awaitTermination(t);
309 >        assertEquals(SIZE, q.size());
310 >        assertEquals(0, q.remainingCapacity());
311      }
312  
313      /**
314 <     * put blocks waiting for take when full
314 >     * put blocks interruptibly waiting for take when full
315       */
316      public void testPutWithTake() throws InterruptedException {
317 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
318 <        Thread t = new Thread(new CheckedRunnable() {
319 <            public void realRun() {
320 <                int added = 0;
317 >        final int capacity = 2;
318 >        final ArrayBlockingQueue q = new ArrayBlockingQueue(capacity);
319 >        final CountDownLatch pleaseTake = new CountDownLatch(1);
320 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
321 >        Thread t = newStartedThread(new CheckedRunnable() {
322 >            public void realRun() throws InterruptedException {
323 >                for (int i = 0; i < capacity; i++)
324 >                    q.put(i);
325 >                pleaseTake.countDown();
326 >                q.put(86);
327 >
328 >                pleaseInterrupt.countDown();
329                  try {
330 <                    q.put(new Object());
331 <                    ++added;
332 <                    q.put(new Object());
333 <                    ++added;
334 <                    q.put(new Object());
335 <                    ++added;
336 <                    q.put(new Object());
337 <                    ++added;
338 <                    threadShouldThrow();
339 <                } catch (InterruptedException e) {
340 <                    threadAssertTrue(added >= 2);
341 <                }
330 >                    q.put(99);
331 >                    shouldThrow();
332 >                } catch (InterruptedException success) {}
333 >                assertFalse(Thread.interrupted());
334              }});
335  
336 <        t.start();
337 <        Thread.sleep(SHORT_DELAY_MS);
338 <        q.take();
336 >        await(pleaseTake);
337 >        assertEquals(0, q.remainingCapacity());
338 >        assertEquals(0, q.take());
339 >
340 >        await(pleaseInterrupt);
341 >        assertThreadStaysAlive(t);
342          t.interrupt();
343 <        t.join();
343 >        awaitTermination(t);
344 >        assertEquals(0, q.remainingCapacity());
345      }
346  
347      /**
# Line 353 | Line 349 | public class ArrayBlockingQueueTest exte
349       */
350      public void testTimedOffer() throws InterruptedException {
351          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
352 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
352 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
353 >        Thread t = newStartedThread(new CheckedRunnable() {
354              public void realRun() throws InterruptedException {
355                  q.put(new Object());
356                  q.put(new Object());
357 <                threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS/2, MILLISECONDS));
358 <                q.offer(new Object(), LONG_DELAY_MS, MILLISECONDS);
359 <            }};
357 >                long startTime = System.nanoTime();
358 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
359 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
360 >                pleaseInterrupt.countDown();
361 >                try {
362 >                    q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
363 >                    shouldThrow();
364 >                } catch (InterruptedException success) {}
365 >            }});
366  
367 <        t.start();
368 <        Thread.sleep(SHORT_DELAY_MS);
367 >        await(pleaseInterrupt);
368 >        assertThreadStaysAlive(t);
369          t.interrupt();
370 <        t.join();
370 >        awaitTermination(t);
371      }
372  
373      /**
# Line 373 | Line 376 | public class ArrayBlockingQueueTest exte
376      public void testTake() throws InterruptedException {
377          ArrayBlockingQueue q = populatedQueue(SIZE);
378          for (int i = 0; i < SIZE; ++i) {
379 <            assertEquals(i, ((Integer)q.take()).intValue());
379 >            assertEquals(i, q.take());
380          }
381      }
382  
383      /**
381     * take blocks interruptibly when empty
382     */
383    public void testTakeFromEmpty() throws InterruptedException {
384        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
385        Thread t = new ThreadShouldThrow(InterruptedException.class) {
386            public void realRun() throws InterruptedException {
387                q.take();
388            }};
389
390        t.start();
391        Thread.sleep(SHORT_DELAY_MS);
392        t.interrupt();
393        t.join();
394    }
395
396    /**
384       * Take removes existing elements until empty, then blocks interruptibly
385       */
386      public void testBlockingTake() throws InterruptedException {
387 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
387 >        final ArrayBlockingQueue q = populatedQueue(SIZE);
388 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
389 >        Thread t = newStartedThread(new CheckedRunnable() {
390              public void realRun() throws InterruptedException {
402                ArrayBlockingQueue q = populatedQueue(SIZE);
391                  for (int i = 0; i < SIZE; ++i) {
392 <                    threadAssertEquals(i, ((Integer)q.take()).intValue());
392 >                    assertEquals(i, q.take());
393                  }
406                q.take();
407            }};
394  
395 <        t.start();
396 <            Thread.sleep(SHORT_DELAY_MS);
397 <            t.interrupt();
398 <            t.join();
399 <    }
395 >                Thread.currentThread().interrupt();
396 >                try {
397 >                    q.take();
398 >                    shouldThrow();
399 >                } catch (InterruptedException success) {}
400 >                assertFalse(Thread.interrupted());
401 >
402 >                pleaseInterrupt.countDown();
403 >                try {
404 >                    q.take();
405 >                    shouldThrow();
406 >                } catch (InterruptedException success) {}
407 >                assertFalse(Thread.interrupted());
408 >            }});
409  
410 +        await(pleaseInterrupt);
411 +        assertThreadStaysAlive(t);
412 +        t.interrupt();
413 +        awaitTermination(t);
414 +    }
415  
416      /**
417       * poll succeeds unless empty
# Line 419 | Line 419 | public class ArrayBlockingQueueTest exte
419      public void testPoll() {
420          ArrayBlockingQueue q = populatedQueue(SIZE);
421          for (int i = 0; i < SIZE; ++i) {
422 <            assertEquals(i, ((Integer)q.poll()).intValue());
422 >            assertEquals(i, q.poll());
423          }
424          assertNull(q.poll());
425      }
426  
427      /**
428 <     * timed pool with zero timeout succeeds when non-empty, else times out
428 >     * timed poll with zero timeout succeeds when non-empty, else times out
429       */
430      public void testTimedPoll0() throws InterruptedException {
431          ArrayBlockingQueue q = populatedQueue(SIZE);
432          for (int i = 0; i < SIZE; ++i) {
433 <            assertEquals(i, ((Integer)q.poll(0, MILLISECONDS)).intValue());
433 >            assertEquals(i, q.poll(0, MILLISECONDS));
434          }
435          assertNull(q.poll(0, MILLISECONDS));
436 +        checkEmpty(q);
437      }
438  
439      /**
440 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
440 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
441       */
442      public void testTimedPoll() throws InterruptedException {
443          ArrayBlockingQueue q = populatedQueue(SIZE);
444          for (int i = 0; i < SIZE; ++i) {
445 <            assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, MILLISECONDS)).intValue());
446 <        }
447 <        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
445 >            long startTime = System.nanoTime();
446 >            assertEquals(i, q.poll(LONG_DELAY_MS, MILLISECONDS));
447 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
448 >        }
449 >        long startTime = System.nanoTime();
450 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
451 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
452 >        checkEmpty(q);
453      }
454  
455      /**
# Line 451 | Line 457 | public class ArrayBlockingQueueTest exte
457       * returning timeout status
458       */
459      public void testInterruptedTimedPoll() throws InterruptedException {
460 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
460 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
461 >        final CountDownLatch aboutToWait = new CountDownLatch(1);
462 >        Thread t = newStartedThread(new CheckedRunnable() {
463              public void realRun() throws InterruptedException {
464 <                ArrayBlockingQueue q = populatedQueue(SIZE);
464 >                long startTime = System.nanoTime();
465                  for (int i = 0; i < SIZE; ++i) {
466 <                    threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, MILLISECONDS)).intValue());
466 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
467                  }
468 <                q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
469 <            }};
470 <
471 <        t.start();
472 <        Thread.sleep(SMALL_DELAY_MS);
473 <        t.interrupt();
474 <        t.join();
475 <    }
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 ThreadShouldThrow(InterruptedException.class) {
476 <            public void realRun() throws InterruptedException {
477 <                threadAssertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
478 <                q.poll(LONG_DELAY_MS, MILLISECONDS);
479 <                q.poll(LONG_DELAY_MS, MILLISECONDS);
480 <            }};
468 >                aboutToWait.countDown();
469 >                try {
470 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
471 >                    shouldThrow();
472 >                } catch (InterruptedException success) {
473 >                    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
474 >                }
475 >            }});
476  
477 <        t.start();
478 <        Thread.sleep(SMALL_DELAY_MS);
484 <        assertTrue(q.offer(zero, SHORT_DELAY_MS, MILLISECONDS));
477 >        await(aboutToWait);
478 >        waitForThreadToEnterWaitState(t);
479          t.interrupt();
480 <        t.join();
480 >        awaitTermination(t);
481 >        checkEmpty(q);
482      }
483  
489
484      /**
485       * peek returns next element, or null if empty
486       */
487      public void testPeek() {
488          ArrayBlockingQueue q = populatedQueue(SIZE);
489          for (int i = 0; i < SIZE; ++i) {
490 <            assertEquals(i, ((Integer)q.peek()).intValue());
491 <            q.poll();
490 >            assertEquals(i, q.peek());
491 >            assertEquals(i, q.poll());
492              assertTrue(q.peek() == null ||
493 <                       i != ((Integer)q.peek()).intValue());
493 >                       !q.peek().equals(i));
494          }
495          assertNull(q.peek());
496      }
# Line 507 | Line 501 | public class ArrayBlockingQueueTest exte
501      public void testElement() {
502          ArrayBlockingQueue q = populatedQueue(SIZE);
503          for (int i = 0; i < SIZE; ++i) {
504 <            assertEquals(i, ((Integer)q.element()).intValue());
505 <            q.poll();
504 >            assertEquals(i, q.element());
505 >            assertEquals(i, q.poll());
506          }
507          try {
508              q.element();
# Line 522 | Line 516 | public class ArrayBlockingQueueTest exte
516      public void testRemove() {
517          ArrayBlockingQueue q = populatedQueue(SIZE);
518          for (int i = 0; i < SIZE; ++i) {
519 <            assertEquals(i, ((Integer)q.remove()).intValue());
519 >            assertEquals(i, q.remove());
520          }
521          try {
522              q.remove();
# Line 531 | Line 525 | public class ArrayBlockingQueueTest exte
525      }
526  
527      /**
534     * remove(x) removes x and returns true if present
535     */
536    public void testRemoveElement() {
537        ArrayBlockingQueue q = populatedQueue(SIZE);
538        for (int i = 1; i < SIZE; i+=2) {
539            assertTrue(q.remove(new Integer(i)));
540        }
541        for (int i = 0; i < SIZE; i+=2) {
542            assertTrue(q.remove(new Integer(i)));
543            assertFalse(q.remove(new Integer(i+1)));
544        }
545        assertTrue(q.isEmpty());
546    }
547
548    /**
528       * contains(x) reports true when elements added but not yet removed
529       */
530      public void testContains() {
531          ArrayBlockingQueue q = populatedQueue(SIZE);
532          for (int i = 0; i < SIZE; ++i) {
533              assertTrue(q.contains(new Integer(i)));
534 <            q.poll();
534 >            assertEquals(i, q.poll());
535              assertFalse(q.contains(new Integer(i)));
536          }
537      }
# Line 601 | Line 580 | public class ArrayBlockingQueueTest exte
580                  assertTrue(changed);
581  
582              assertTrue(q.containsAll(p));
583 <            assertEquals(SIZE-i, q.size());
583 >            assertEquals(SIZE - i, q.size());
584              p.remove();
585          }
586      }
# Line 614 | Line 593 | public class ArrayBlockingQueueTest exte
593              ArrayBlockingQueue q = populatedQueue(SIZE);
594              ArrayBlockingQueue p = populatedQueue(i);
595              assertTrue(q.removeAll(p));
596 <            assertEquals(SIZE-i, q.size());
596 >            assertEquals(SIZE - i, q.size());
597              for (int j = 0; j < i; ++j) {
598 <                Integer I = (Integer)(p.remove());
599 <                assertFalse(q.contains(I));
598 >                Integer x = (Integer)(p.remove());
599 >                assertFalse(q.contains(x));
600              }
601          }
602      }
603  
604 <    /**
605 <     *  toArray contains all elements
606 <     */
607 <    public void testToArray() throws InterruptedException {
608 <        ArrayBlockingQueue q = populatedQueue(SIZE);
609 <        Object[] o = q.toArray();
610 <        for (int i = 0; i < o.length; i++)
611 <            assertEquals(o[i], q.take());
604 >    void checkToArray(ArrayBlockingQueue<Integer> q) {
605 >        int size = q.size();
606 >        Object[] a1 = q.toArray();
607 >        assertEquals(size, a1.length);
608 >        Integer[] a2 = q.toArray(new Integer[0]);
609 >        assertEquals(size, a2.length);
610 >        Integer[] a3 = q.toArray(new Integer[Math.max(0, size - 1)]);
611 >        assertEquals(size, a3.length);
612 >        Integer[] a4 = new Integer[size];
613 >        assertSame(a4, q.toArray(a4));
614 >        Integer[] a5 = new Integer[size + 1];
615 >        Arrays.fill(a5, 42);
616 >        assertSame(a5, q.toArray(a5));
617 >        Integer[] a6 = new Integer[size + 2];
618 >        Arrays.fill(a6, 42);
619 >        assertSame(a6, q.toArray(a6));
620 >        Object[][] as = { a1, a2, a3, a4, a5, a6 };
621 >        for (Object[] a : as) {
622 >            if (a.length > size) assertNull(a[size]);
623 >            if (a.length > size + 1) assertEquals(42, a[size + 1]);
624 >        }
625 >        Iterator it = q.iterator();
626 >        Integer s = q.peek();
627 >        for (int i = 0; i < size; i++) {
628 >            Integer x = (Integer) it.next();
629 >            assertEquals(s + i, (int) x);
630 >            for (Object[] a : as)
631 >                assertSame(a1[i], x);
632 >        }
633      }
634  
635      /**
636 <     * toArray(a) contains all elements
636 >     * toArray() and toArray(a) contain all elements in FIFO order
637       */
638 <    public void testToArray2() throws InterruptedException {
639 <        ArrayBlockingQueue q = populatedQueue(SIZE);
640 <        Integer[] ints = new Integer[SIZE];
641 <        ints = (Integer[])q.toArray(ints);
642 <        for (int i = 0; i < ints.length; i++)
643 <            assertEquals(ints[i], q.take());
638 >    public void testToArray() {
639 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
640 >        final int size = rnd.nextInt(6);
641 >        final int capacity = Math.max(1, size + rnd.nextInt(size + 1));
642 >        ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(capacity);
643 >        for (int i = 0; i < size; i++) {
644 >            checkToArray(q);
645 >            q.add(i);
646 >        }
647 >        // Provoke wraparound
648 >        int added = size * 2;
649 >        for (int i = 0; i < added; i++) {
650 >            checkToArray(q);
651 >            assertEquals((Integer) i, q.poll());
652 >            q.add(size + i);
653 >        }
654 >        for (int i = 0; i < size; i++) {
655 >            checkToArray(q);
656 >            assertEquals((Integer) (added + i), q.poll());
657 >        }
658      }
659  
660      /**
661 <     * toArray(null) throws NPE
661 >     * toArray(incompatible array type) throws ArrayStoreException
662       */
663 <    public void testToArray_BadArg() {
663 >    public void testToArray_incompatibleArrayType() {
664 >        ArrayBlockingQueue q = populatedQueue(SIZE);
665          try {
666 <            ArrayBlockingQueue q = populatedQueue(SIZE);
652 <            Object o[] = q.toArray(null);
666 >            q.toArray(new String[10]);
667              shouldThrow();
668 <        } catch (NullPointerException success) {}
655 <    }
656 <
657 <    /**
658 <     * toArray with incompatible array type throws CCE
659 <     */
660 <    public void testToArray1_BadArg() {
668 >        } catch (ArrayStoreException success) {}
669          try {
670 <            ArrayBlockingQueue q = populatedQueue(SIZE);
663 <            Object o[] = q.toArray(new String[10] );
670 >            q.toArray(new String[0]);
671              shouldThrow();
672          } catch (ArrayStoreException success) {}
673      }
674  
668
675      /**
676       * iterator iterates through all elements
677       */
678      public void testIterator() throws InterruptedException {
679          ArrayBlockingQueue q = populatedQueue(SIZE);
680          Iterator it = q.iterator();
681 <        while (it.hasNext()) {
681 >        int i;
682 >        for (i = 0; it.hasNext(); i++)
683 >            assertTrue(q.contains(it.next()));
684 >        assertEquals(i, SIZE);
685 >        assertIteratorExhausted(it);
686 >
687 >        it = q.iterator();
688 >        for (i = 0; it.hasNext(); i++)
689              assertEquals(it.next(), q.take());
690 <        }
690 >        assertEquals(i, SIZE);
691 >        assertIteratorExhausted(it);
692 >    }
693 >
694 >    /**
695 >     * iterator of empty collection has no elements
696 >     */
697 >    public void testEmptyIterator() {
698 >        assertIteratorExhausted(new ArrayBlockingQueue(SIZE).iterator());
699      }
700  
701      /**
702       * iterator.remove removes current element
703       */
704 <    public void testIteratorRemove () {
704 >    public void testIteratorRemove() {
705          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
706          q.add(two);
707          q.add(one);
# Line 691 | Line 712 | public class ArrayBlockingQueueTest exte
712          it.remove();
713  
714          it = q.iterator();
715 <        assertEquals(it.next(), one);
716 <        assertEquals(it.next(), three);
715 >        assertSame(it.next(), one);
716 >        assertSame(it.next(), three);
717          assertFalse(it.hasNext());
718      }
719  
# Line 709 | Line 730 | public class ArrayBlockingQueueTest exte
730  
731          int k = 0;
732          for (Iterator it = q.iterator(); it.hasNext();) {
733 <            int i = ((Integer)(it.next())).intValue();
713 <            assertEquals(++k, i);
733 >            assertEquals(++k, it.next());
734          }
735          assertEquals(3, k);
736      }
# Line 718 | Line 738 | public class ArrayBlockingQueueTest exte
738      /**
739       * Modifications do not cause iterators to fail
740       */
741 <    public void testWeaklyConsistentIteration () {
741 >    public void testWeaklyConsistentIteration() {
742          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
743          q.add(one);
744          q.add(two);
# Line 730 | Line 750 | public class ArrayBlockingQueueTest exte
750          assertEquals(0, q.size());
751      }
752  
733
753      /**
754       * toString contains toStrings of elements
755       */
# Line 738 | Line 757 | public class ArrayBlockingQueueTest exte
757          ArrayBlockingQueue q = populatedQueue(SIZE);
758          String s = q.toString();
759          for (int i = 0; i < SIZE; ++i) {
760 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
760 >            assertTrue(s.contains(String.valueOf(i)));
761          }
762      }
763  
745
764      /**
765       * offer transfers elements across Executor tasks
766       */
# Line 750 | Line 768 | public class ArrayBlockingQueueTest exte
768          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
769          q.add(one);
770          q.add(two);
771 <        ExecutorService executor = Executors.newFixedThreadPool(2);
772 <        executor.execute(new CheckedRunnable() {
773 <            public void realRun() throws InterruptedException {
774 <                threadAssertFalse(q.offer(three));
775 <                threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
776 <                threadAssertEquals(0, q.remainingCapacity());
777 <            }});
778 <
779 <        executor.execute(new CheckedRunnable() {
780 <            public void realRun() throws InterruptedException {
781 <                Thread.sleep(SMALL_DELAY_MS);
782 <                threadAssertEquals(one, q.take());
783 <            }});
784 <
785 <        joinPool(executor);
786 <
771 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
772 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
773 >        try (PoolCleaner cleaner = cleaner(executor)) {
774 >            executor.execute(new CheckedRunnable() {
775 >                public void realRun() throws InterruptedException {
776 >                    assertFalse(q.offer(three));
777 >                    threadsStarted.await();
778 >                    assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
779 >                    assertEquals(0, q.remainingCapacity());
780 >                }});
781 >
782 >            executor.execute(new CheckedRunnable() {
783 >                public void realRun() throws InterruptedException {
784 >                    threadsStarted.await();
785 >                    assertEquals(0, q.remainingCapacity());
786 >                    assertSame(one, q.take());
787 >                }});
788 >        }
789      }
790  
791      /**
792 <     * poll retrieves elements across Executor threads
792 >     * timed poll retrieves elements across Executor threads
793       */
794      public void testPollInExecutor() {
795          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
796 <        ExecutorService executor = Executors.newFixedThreadPool(2);
797 <        executor.execute(new CheckedRunnable() {
798 <            public void realRun() throws InterruptedException {
799 <                threadAssertNull(q.poll());
800 <                threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
801 <                threadAssertTrue(q.isEmpty());
802 <            }});
803 <
804 <        executor.execute(new CheckedRunnable() {
805 <            public void realRun() throws InterruptedException {
806 <                Thread.sleep(SMALL_DELAY_MS);
807 <                q.put(one);
808 <            }});
809 <
810 <        joinPool(executor);
796 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
797 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
798 >        try (PoolCleaner cleaner = cleaner(executor)) {
799 >            executor.execute(new CheckedRunnable() {
800 >                public void realRun() throws InterruptedException {
801 >                    assertNull(q.poll());
802 >                    threadsStarted.await();
803 >                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
804 >                    checkEmpty(q);
805 >                }});
806 >
807 >            executor.execute(new CheckedRunnable() {
808 >                public void realRun() throws InterruptedException {
809 >                    threadsStarted.await();
810 >                    q.put(one);
811 >                }});
812 >        }
813      }
814  
815      /**
816       * A deserialized serialized queue has same elements in same order
817       */
818      public void testSerialization() throws Exception {
819 <        ArrayBlockingQueue q = populatedQueue(SIZE);
820 <
799 <        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
800 <        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
801 <        out.writeObject(q);
802 <        out.close();
803 <
804 <        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
805 <        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
806 <        ArrayBlockingQueue r = (ArrayBlockingQueue)in.readObject();
807 <        assertEquals(q.size(), r.size());
808 <        while (!q.isEmpty())
809 <            assertEquals(q.remove(), r.remove());
810 <    }
811 <
812 <    /**
813 <     * drainTo(null) throws NPE
814 <     */
815 <    public void testDrainToNull() {
816 <        ArrayBlockingQueue q = populatedQueue(SIZE);
817 <        try {
818 <            q.drainTo(null);
819 <            shouldThrow();
820 <        } catch (NullPointerException success) {}
821 <    }
819 >        Queue x = populatedQueue(SIZE);
820 >        Queue y = serialClone(x);
821  
822 <    /**
823 <     * drainTo(this) throws IAE
824 <     */
825 <    public void testDrainToSelf() {
826 <        ArrayBlockingQueue q = populatedQueue(SIZE);
827 <        try {
828 <            q.drainTo(q);
829 <            shouldThrow();
830 <        } catch (IllegalArgumentException success) {}
822 >        assertNotSame(x, y);
823 >        assertEquals(x.size(), y.size());
824 >        assertEquals(x.toString(), y.toString());
825 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
826 >        while (!x.isEmpty()) {
827 >            assertFalse(y.isEmpty());
828 >            assertEquals(x.remove(), y.remove());
829 >        }
830 >        assertTrue(y.isEmpty());
831      }
832  
833      /**
# Line 838 | Line 837 | public class ArrayBlockingQueueTest exte
837          ArrayBlockingQueue q = populatedQueue(SIZE);
838          ArrayList l = new ArrayList();
839          q.drainTo(l);
840 <        assertEquals(q.size(), 0);
841 <        assertEquals(l.size(), SIZE);
840 >        assertEquals(0, q.size());
841 >        assertEquals(SIZE, l.size());
842          for (int i = 0; i < SIZE; ++i)
843              assertEquals(l.get(i), new Integer(i));
844          q.add(zero);
# Line 849 | Line 848 | public class ArrayBlockingQueueTest exte
848          assertTrue(q.contains(one));
849          l.clear();
850          q.drainTo(l);
851 <        assertEquals(q.size(), 0);
852 <        assertEquals(l.size(), 2);
851 >        assertEquals(0, q.size());
852 >        assertEquals(2, l.size());
853          for (int i = 0; i < 2; ++i)
854              assertEquals(l.get(i), new Integer(i));
855      }
# Line 862 | Line 861 | public class ArrayBlockingQueueTest exte
861          final ArrayBlockingQueue q = populatedQueue(SIZE);
862          Thread t = new Thread(new CheckedRunnable() {
863              public void realRun() throws InterruptedException {
864 <                q.put(new Integer(SIZE+1));
864 >                q.put(new Integer(SIZE + 1));
865              }});
866  
867          t.start();
# Line 876 | Line 875 | public class ArrayBlockingQueueTest exte
875      }
876  
877      /**
878 <     * drainTo(null, n) throws NPE
880 <     */
881 <    public void testDrainToNullN() {
882 <        ArrayBlockingQueue q = populatedQueue(SIZE);
883 <        try {
884 <            q.drainTo(null, 0);
885 <            shouldThrow();
886 <        } catch (NullPointerException success) {}
887 <    }
888 <
889 <    /**
890 <     * drainTo(this, n) throws IAE
891 <     */
892 <    public void testDrainToSelfN() {
893 <        ArrayBlockingQueue q = populatedQueue(SIZE);
894 <        try {
895 <            q.drainTo(q, 0);
896 <            shouldThrow();
897 <        } catch (IllegalArgumentException success) {}
898 <    }
899 <
900 <    /**
901 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
878 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
879       */
880      public void testDrainToN() {
881 <        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE*2);
881 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE * 2);
882          for (int i = 0; i < SIZE + 2; ++i) {
883              for (int j = 0; j < SIZE; j++)
884                  assertTrue(q.offer(new Integer(j)));
885              ArrayList l = new ArrayList();
886              q.drainTo(l, i);
887 <            int k = (i < SIZE)? i : SIZE;
888 <            assertEquals(l.size(), k);
889 <            assertEquals(q.size(), SIZE-k);
887 >            int k = (i < SIZE) ? i : SIZE;
888 >            assertEquals(k, l.size());
889 >            assertEquals(SIZE - k, q.size());
890              for (int j = 0; j < k; ++j)
891                  assertEquals(l.get(j), new Integer(j));
892 <            while (q.poll() != null) ;
892 >            do {} while (q.poll() != null);
893          }
894      }
895  
896 +    /**
897 +     * remove(null), contains(null) always return false
898 +     */
899 +    public void testNeverContainsNull() {
900 +        Collection<?>[] qs = {
901 +            new ArrayBlockingQueue<Object>(10),
902 +            populatedQueue(2),
903 +        };
904 +
905 +        for (Collection<?> q : qs) {
906 +            assertFalse(q.contains(null));
907 +            assertFalse(q.remove(null));
908 +        }
909 +    }
910   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines