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.3 by dl, Sun Sep 14 20:42:40 2003 UTC vs.
Revision 1.46 by jsr166, Sat May 21 06:24:33 2011 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
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/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.*;
13 + import static java.util.concurrent.TimeUnit.MILLISECONDS;
14   import java.io.*;
15  
16   public class ArrayBlockingQueueTest extends JSR166TestCase {
17  
18 +    public static class Fair extends BlockingQueueTest {
19 +        protected BlockingQueue emptyCollection() {
20 +            return new ArrayBlockingQueue(20, true);
21 +        }
22 +    }
23 +
24 +    public static class NonFair extends BlockingQueueTest {
25 +        protected BlockingQueue emptyCollection() {
26 +            return new ArrayBlockingQueue(20, false);
27 +        }
28 +    }
29 +
30      public static void main(String[] args) {
31 <        junit.textui.TestRunner.run (suite());  
31 >        junit.textui.TestRunner.run(suite());
32      }
33  
34      public static Test suite() {
35 <        return new TestSuite(ArrayBlockingQueueTest.class);
35 >        return newTestSuite(ArrayBlockingQueueTest.class,
36 >                            new Fair().testSuite(),
37 >                            new NonFair().testSuite());
38      }
39  
40      /**
41       * Create a queue of given size containing consecutive
42       * Integers 0 ... n.
43       */
44 <    private ArrayBlockingQueue populatedQueue(int n) {
45 <        ArrayBlockingQueue q = new ArrayBlockingQueue(n);
44 >    private ArrayBlockingQueue<Integer> populatedQueue(int n) {
45 >        ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(n);
46          assertTrue(q.isEmpty());
47 <        for(int i = 0; i < n; i++)
48 <            assertTrue(q.offer(new Integer(i)));
47 >        for (int i = 0; i < n; i++)
48 >            assertTrue(q.offer(new Integer(i)));
49          assertFalse(q.isEmpty());
50          assertEquals(0, q.remainingCapacity());
51 <        assertEquals(n, q.size());
51 >        assertEquals(n, q.size());
52          return q;
53      }
54 <
55 <    public void testConstructor1(){
54 >
55 >    /**
56 >     * A new queue has the indicated capacity
57 >     */
58 >    public void testConstructor1() {
59          assertEquals(SIZE, new ArrayBlockingQueue(SIZE).remainingCapacity());
60      }
61  
62 <    public void testConstructor2(){
62 >    /**
63 >     * Constructor throws IAE if capacity argument nonpositive
64 >     */
65 >    public void testConstructor2() {
66          try {
67              ArrayBlockingQueue q = new ArrayBlockingQueue(0);
68 <            fail("Cannot make zero-sized");
69 <        }
47 <        catch (IllegalArgumentException success) {}
68 >            shouldThrow();
69 >        } catch (IllegalArgumentException success) {}
70      }
71  
72 <    public void testConstructor3(){
73 <
72 >    /**
73 >     * Initializing from null Collection throws NPE
74 >     */
75 >    public void testConstructor3() {
76          try {
77              ArrayBlockingQueue q = new ArrayBlockingQueue(1, true, null);
78 <            fail("Cannot make from null collection");
79 <        }
56 <        catch (NullPointerException success) {}
78 >            shouldThrow();
79 >        } catch (NullPointerException success) {}
80      }
81  
82 <    public void testConstructor4(){
82 >    /**
83 >     * Initializing from Collection of null elements throws NPE
84 >     */
85 >    public void testConstructor4() {
86          try {
87              Integer[] ints = new Integer[SIZE];
88              ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
89 <            fail("Cannot make with null elements");
90 <        }
65 <        catch (NullPointerException success) {}
89 >            shouldThrow();
90 >        } catch (NullPointerException success) {}
91      }
92  
93 <    public void testConstructor5(){
93 >    /**
94 >     * Initializing from Collection with some null elements throws NPE
95 >     */
96 >    public void testConstructor5() {
97          try {
98              Integer[] ints = new Integer[SIZE];
99              for (int i = 0; i < SIZE-1; ++i)
100                  ints[i] = new Integer(i);
101              ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, false, Arrays.asList(ints));
102 <            fail("Cannot make with null elements");
103 <        }
76 <        catch (NullPointerException success) {}
102 >            shouldThrow();
103 >        } catch (NullPointerException success) {}
104      }
105  
106 <    public void testConstructor6(){
106 >    /**
107 >     * Initializing from too large collection throws IAE
108 >     */
109 >    public void testConstructor6() {
110          try {
111              Integer[] ints = new Integer[SIZE];
112              for (int i = 0; i < SIZE; ++i)
113                  ints[i] = new Integer(i);
114              ArrayBlockingQueue q = new ArrayBlockingQueue(1, false, Arrays.asList(ints));
115 <            fail("Cannot make with insufficient capacity");
116 <        }
87 <        catch (IllegalArgumentException success) {}
115 >            shouldThrow();
116 >        } catch (IllegalArgumentException success) {}
117      }
118  
119 <    public void testConstructor7(){
120 <        try {
121 <            Integer[] ints = new Integer[SIZE];
122 <            for (int i = 0; i < SIZE; ++i)
123 <                ints[i] = new Integer(i);
124 <            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, Arrays.asList(ints));
125 <            for (int i = 0; i < SIZE; ++i)
126 <                assertEquals(ints[i], q.poll());
127 <        }
128 <        finally {}
119 >    /**
120 >     * Queue contains all elements of collection used to initialize
121 >     */
122 >    public void testConstructor7() {
123 >        Integer[] ints = new Integer[SIZE];
124 >        for (int i = 0; i < SIZE; ++i)
125 >            ints[i] = new Integer(i);
126 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE, true, Arrays.asList(ints));
127 >        for (int i = 0; i < SIZE; ++i)
128 >            assertEquals(ints[i], q.poll());
129      }
130  
131 +    /**
132 +     * Queue transitions from empty to full when elements added
133 +     */
134      public void testEmptyFull() {
135          ArrayBlockingQueue q = new ArrayBlockingQueue(2);
136          assertTrue(q.isEmpty());
137 <        assertEquals("should have room for 2", 2, q.remainingCapacity());
137 >        assertEquals(2, q.remainingCapacity());
138          q.add(one);
139          assertFalse(q.isEmpty());
140          q.add(two);
141          assertFalse(q.isEmpty());
142 <        assertEquals("queue should be full", 0, q.remainingCapacity());
143 <        assertFalse("offer should be rejected", q.offer(three));
142 >        assertEquals(0, q.remainingCapacity());
143 >        assertFalse(q.offer(three));
144      }
145  
146 <    public void testRemainingCapacity(){
146 >    /**
147 >     * remainingCapacity decreases on add, increases on remove
148 >     */
149 >    public void testRemainingCapacity() {
150          ArrayBlockingQueue q = populatedQueue(SIZE);
151          for (int i = 0; i < SIZE; ++i) {
152              assertEquals(i, q.remainingCapacity());
# Line 125 | Line 160 | public class ArrayBlockingQueueTest exte
160          }
161      }
162  
163 <    public void testOfferNull(){
164 <        try {
163 >    /**
164 >     * offer(null) throws NPE
165 >     */
166 >    public void testOfferNull() {
167 >        try {
168              ArrayBlockingQueue q = new ArrayBlockingQueue(1);
169              q.offer(null);
170 <            fail("should throw NPE");
171 <        } catch (NullPointerException success) { }  
170 >            shouldThrow();
171 >        } catch (NullPointerException success) {}
172      }
173  
174 <    public void testOffer(){
174 >    /**
175 >     * add(null) throws NPE
176 >     */
177 >    public void testAddNull() {
178 >        try {
179 >            ArrayBlockingQueue q = new ArrayBlockingQueue(1);
180 >            q.add(null);
181 >            shouldThrow();
182 >        } catch (NullPointerException success) {}
183 >    }
184 >
185 >    /**
186 >     * Offer succeeds if not full; fails if full
187 >     */
188 >    public void testOffer() {
189          ArrayBlockingQueue q = new ArrayBlockingQueue(1);
190          assertTrue(q.offer(zero));
191          assertFalse(q.offer(one));
192      }
193  
194 <    public void testAdd(){
195 <        try {
194 >    /**
195 >     * add succeeds if not full; throws ISE if full
196 >     */
197 >    public void testAdd() {
198 >        try {
199              ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
200              for (int i = 0; i < SIZE; ++i) {
201                  assertTrue(q.add(new Integer(i)));
202              }
203              assertEquals(0, q.remainingCapacity());
204              q.add(new Integer(SIZE));
205 <        } catch (IllegalStateException success){
206 <        }  
205 >            shouldThrow();
206 >        } catch (IllegalStateException success) {}
207      }
208  
209 <    public void testAddAll1(){
209 >    /**
210 >     * addAll(null) throws NPE
211 >     */
212 >    public void testAddAll1() {
213          try {
214              ArrayBlockingQueue q = new ArrayBlockingQueue(1);
215              q.addAll(null);
216 <            fail("Cannot add null collection");
217 <        }
160 <        catch (NullPointerException success) {}
216 >            shouldThrow();
217 >        } catch (NullPointerException success) {}
218      }
219 <    public void testAddAll2(){
219 >
220 >    /**
221 >     * addAll(this) throws IAE
222 >     */
223 >    public void testAddAllSelf() {
224 >        try {
225 >            ArrayBlockingQueue q = populatedQueue(SIZE);
226 >            q.addAll(q);
227 >            shouldThrow();
228 >        } catch (IllegalArgumentException success) {}
229 >    }
230 >
231 >
232 >    /**
233 >     * addAll of a collection with null elements throws NPE
234 >     */
235 >    public void testAddAll2() {
236          try {
237              ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
238              Integer[] ints = new Integer[SIZE];
239              q.addAll(Arrays.asList(ints));
240 <            fail("Cannot add null elements");
241 <        }
169 <        catch (NullPointerException success) {}
240 >            shouldThrow();
241 >        } catch (NullPointerException success) {}
242      }
243 <    public void testAddAll3(){
243 >
244 >    /**
245 >     * addAll of a collection with any null elements throws NPE after
246 >     * possibly adding some elements
247 >     */
248 >    public void testAddAll3() {
249          try {
250              ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
251              Integer[] ints = new Integer[SIZE];
252              for (int i = 0; i < SIZE-1; ++i)
253                  ints[i] = new Integer(i);
254              q.addAll(Arrays.asList(ints));
255 <            fail("Cannot add null elements");
256 <        }
180 <        catch (NullPointerException success) {}
255 >            shouldThrow();
256 >        } catch (NullPointerException success) {}
257      }
258 <    public void testAddAll4(){
258 >
259 >    /**
260 >     * addAll throws ISE if not enough room
261 >     */
262 >    public void testAddAll4() {
263          try {
264              ArrayBlockingQueue q = new ArrayBlockingQueue(1);
265              Integer[] ints = new Integer[SIZE];
266              for (int i = 0; i < SIZE; ++i)
267                  ints[i] = new Integer(i);
268              q.addAll(Arrays.asList(ints));
269 <            fail("Cannot add with insufficient capacity");
270 <        }
191 <        catch (IllegalStateException success) {}
269 >            shouldThrow();
270 >        } catch (IllegalStateException success) {}
271      }
272 <    public void testAddAll5(){
273 <        try {
274 <            Integer[] empty = new Integer[0];
275 <            Integer[] ints = new Integer[SIZE];
276 <            for (int i = 0; i < SIZE; ++i)
277 <                ints[i] = new Integer(i);
278 <            ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
279 <            assertFalse(q.addAll(Arrays.asList(empty)));
280 <            assertTrue(q.addAll(Arrays.asList(ints)));
281 <            for (int i = 0; i < SIZE; ++i)
282 <                assertEquals(ints[i], q.poll());
283 <        }
284 <        finally {}
272 >
273 >    /**
274 >     * Queue contains all elements, in traversal order, of successful addAll
275 >     */
276 >    public void testAddAll5() {
277 >        Integer[] empty = new Integer[0];
278 >        Integer[] ints = new Integer[SIZE];
279 >        for (int i = 0; i < SIZE; ++i)
280 >            ints[i] = new Integer(i);
281 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
282 >        assertFalse(q.addAll(Arrays.asList(empty)));
283 >        assertTrue(q.addAll(Arrays.asList(ints)));
284 >        for (int i = 0; i < SIZE; ++i)
285 >            assertEquals(ints[i], q.poll());
286      }
287  
288 <     public void testPutNull() {
289 <        try {
288 >    /**
289 >     * put(null) throws NPE
290 >     */
291 >    public void testPutNull() throws InterruptedException {
292 >        try {
293              ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
294              q.put(null);
295 <            fail("put should throw NPE");
296 <        }
214 <        catch (NullPointerException success){
215 <        }  
216 <        catch (InterruptedException ie) {
217 <            fail("Unexpected exception");
218 <        }
219 <     }
220 <
221 <     public void testPut() {
222 <         try {
223 <             ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
224 <             for (int i = 0; i < SIZE; ++i) {
225 <                 Integer I = new Integer(i);
226 <                 q.put(I);
227 <                 assertTrue(q.contains(I));
228 <             }
229 <             assertEquals(0, q.remainingCapacity());
230 <         }
231 <        catch (InterruptedException ie) {
232 <            fail("Unexpected exception");
233 <        }
295 >            shouldThrow();
296 >        } catch (NullPointerException success) {}
297      }
298  
299 <    public void testBlockingPut(){
300 <        Thread t = new Thread(new Runnable() {
301 <                public void run() {
302 <                    int added = 0;
303 <                    try {
304 <                        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
305 <                        for (int i = 0; i < SIZE; ++i) {
306 <                            q.put(new Integer(i));
307 <                            ++added;
245 <                        }
246 <                        q.put(new Integer(SIZE));
247 <                        threadFail("put should block");
248 <                    } catch (InterruptedException ie){
249 <                        threadAssertEquals(added, SIZE);
250 <                    }  
251 <                }});
252 <        try {
253 <            t.start();
254 <           Thread.sleep(SHORT_DELAY_MS);
255 <           t.interrupt();
256 <           t.join();
257 <        }
258 <        catch (InterruptedException ie) {
259 <            fail("Unexpected exception");
299 >    /**
300 >     * all elements successfully put are contained
301 >     */
302 >    public void testPut() throws InterruptedException {
303 >        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
304 >        for (int i = 0; i < SIZE; ++i) {
305 >            Integer I = new Integer(i);
306 >            q.put(I);
307 >            assertTrue(q.contains(I));
308          }
309 +        assertEquals(0, q.remainingCapacity());
310      }
311  
312 <    public void testPutWithTake() {
313 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
314 <        Thread t = new Thread(new Runnable() {
315 <                public void run(){
316 <                    int added = 0;
317 <                    try {
318 <                        q.put(new Object());
319 <                        ++added;
320 <                        q.put(new Object());
321 <                        ++added;
322 <                        q.put(new Object());
323 <                        ++added;
324 <                        q.put(new Object());
325 <                        ++added;
326 <                        threadFail("Should block");
327 <                    } catch (InterruptedException e){
328 <                        threadAssertTrue(added >= 2);
329 <                    }
330 <                }
331 <            });
332 <        try {
333 <            t.start();
334 <            Thread.sleep(SHORT_DELAY_MS);
286 <            q.take();
287 <            t.interrupt();
288 <            t.join();
289 <        } catch (Exception e){
290 <            fail("Unexpected exception");
291 <        }
312 >    /**
313 >     * put blocks interruptibly if full
314 >     */
315 >    public void testBlockingPut() throws InterruptedException {
316 >        final ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE);
317 >        Thread t = new Thread(new CheckedRunnable() {
318 >            public void realRun() throws InterruptedException {
319 >                for (int i = 0; i < SIZE; ++i)
320 >                    q.put(i);
321 >                assertEquals(SIZE, q.size());
322 >                assertEquals(0, q.remainingCapacity());
323 >                try {
324 >                    q.put(99);
325 >                    shouldThrow();
326 >                } catch (InterruptedException success) {}
327 >            }});
328 >
329 >        t.start();
330 >        delay(SHORT_DELAY_MS);
331 >        t.interrupt();
332 >        t.join();
333 >        assertEquals(SIZE, q.size());
334 >        assertEquals(0, q.remainingCapacity());
335      }
336  
337 <    public void testTimedOffer() {
338 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
339 <        Thread t = new Thread(new Runnable() {
340 <                public void run(){
341 <                    try {
342 <                        q.put(new Object());
343 <                        q.put(new Object());
344 <                        threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS));
345 <                        q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
346 <                        threadFail("Should block");
347 <                    } catch (InterruptedException success){}
348 <                }
349 <            });
350 <        
351 <        try {
352 <            t.start();
353 <            Thread.sleep(SHORT_DELAY_MS);
354 <            t.interrupt();
355 <            t.join();
356 <        } catch (Exception e){
357 <            fail("Unexpected exception");
358 <        }
337 >    /**
338 >     * put blocks waiting for take when full
339 >     */
340 >    public void testPutWithTake() throws InterruptedException {
341 >        final int capacity = 2;
342 >        final ArrayBlockingQueue q = new ArrayBlockingQueue(capacity);
343 >        Thread t = new Thread(new CheckedRunnable() {
344 >            public void realRun() throws InterruptedException {
345 >                for (int i = 0; i < capacity + 1; i++)
346 >                    q.put(i);
347 >                try {
348 >                    q.put(99);
349 >                    shouldThrow();
350 >                } catch (InterruptedException success) {}
351 >            }});
352 >
353 >        t.start();
354 >        delay(SHORT_DELAY_MS);
355 >        assertEquals(q.remainingCapacity(), 0);
356 >        assertEquals(0, q.take());
357 >        delay(SHORT_DELAY_MS);
358 >        t.interrupt();
359 >        t.join();
360 >        assertEquals(q.remainingCapacity(), 0);
361      }
362  
363 <    public void testTake(){
364 <        try {
365 <            ArrayBlockingQueue q = populatedQueue(SIZE);
366 <            for (int i = 0; i < SIZE; ++i) {
367 <                assertEquals(i, ((Integer)q.take()).intValue());
368 <            }
369 <        } catch (InterruptedException e){
370 <            fail("Unexpected exception");
371 <        }  
363 >    /**
364 >     * timed offer times out if full and elements not taken
365 >     */
366 >    public void testTimedOffer() throws InterruptedException {
367 >        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
368 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
369 >        Thread t = newStartedThread(new CheckedRunnable() {
370 >            public void realRun() throws InterruptedException {
371 >                q.put(new Object());
372 >                q.put(new Object());
373 >                long startTime = System.nanoTime();
374 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
375 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
376 >                pleaseInterrupt.countDown();
377 >                try {
378 >                    q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
379 >                    shouldThrow();
380 >                } catch (InterruptedException success) {}
381 >            }});
382 >
383 >        await(pleaseInterrupt);
384 >        t.interrupt();
385 >        awaitTermination(t);
386      }
387  
388 <    public void testTakeFromEmpty() {
389 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
390 <        Thread t = new Thread(new Runnable() {
391 <                public void run(){
392 <                    try {
393 <                        q.take();
394 <                        threadFail("Should block");
336 <                    } catch (InterruptedException success){ }                
337 <                }
338 <            });
339 <        try {
340 <            t.start();
341 <            Thread.sleep(SHORT_DELAY_MS);
342 <            t.interrupt();
343 <            t.join();
344 <        } catch (Exception e){
345 <            fail("Unexpected exception");
388 >    /**
389 >     * take retrieves elements in FIFO order
390 >     */
391 >    public void testTake() throws InterruptedException {
392 >        ArrayBlockingQueue q = populatedQueue(SIZE);
393 >        for (int i = 0; i < SIZE; ++i) {
394 >            assertEquals(i, q.take());
395          }
396      }
397  
398 <    public void testBlockingTake(){
399 <        Thread t = new Thread(new Runnable() {
400 <                public void run() {
401 <                    try {
402 <                        ArrayBlockingQueue q = populatedQueue(SIZE);
403 <                        for (int i = 0; i < SIZE; ++i) {
404 <                            threadAssertEquals(i, ((Integer)q.take()).intValue());
405 <                        }
406 <                        q.take();
407 <                        threadFail("take should block");
408 <                    } catch (InterruptedException success){
409 <                    }  
410 <                }});
411 <        try {
412 <            t.start();
413 <            Thread.sleep(SHORT_DELAY_MS);
414 <            t.interrupt();
415 <            t.join();
416 <        }
417 <        catch (InterruptedException ie) {
369 <            fail("Unexpected exception");
370 <        }
398 >    /**
399 >     * Take removes existing elements until empty, then blocks interruptibly
400 >     */
401 >    public void testBlockingTake() throws InterruptedException {
402 >        final ArrayBlockingQueue q = populatedQueue(SIZE);
403 >        Thread t = new Thread(new CheckedRunnable() {
404 >            public void realRun() throws InterruptedException {
405 >                for (int i = 0; i < SIZE; ++i) {
406 >                    assertEquals(i, q.take());
407 >                }
408 >                try {
409 >                    q.take();
410 >                    shouldThrow();
411 >                } catch (InterruptedException success) {}
412 >            }});
413 >
414 >        t.start();
415 >        delay(SHORT_DELAY_MS);
416 >        t.interrupt();
417 >        t.join();
418      }
419  
420  
421 <    public void testPoll(){
421 >    /**
422 >     * poll succeeds unless empty
423 >     */
424 >    public void testPoll() {
425          ArrayBlockingQueue q = populatedQueue(SIZE);
426          for (int i = 0; i < SIZE; ++i) {
427 <            assertEquals(i, ((Integer)q.poll()).intValue());
427 >            assertEquals(i, q.poll());
428          }
429 <        assertNull(q.poll());
429 >        assertNull(q.poll());
430      }
431  
432 <    public void testTimedPoll0() {
433 <        try {
434 <            ArrayBlockingQueue q = populatedQueue(SIZE);
435 <            for (int i = 0; i < SIZE; ++i) {
436 <                assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
437 <            }
438 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
439 <        } catch (InterruptedException e){
440 <            fail("Unexpected exception");
391 <        }  
432 >    /**
433 >     * timed poll with zero timeout succeeds when non-empty, else times out
434 >     */
435 >    public void testTimedPoll0() throws InterruptedException {
436 >        ArrayBlockingQueue q = populatedQueue(SIZE);
437 >        for (int i = 0; i < SIZE; ++i) {
438 >            assertEquals(i, q.poll(0, MILLISECONDS));
439 >        }
440 >        assertNull(q.poll(0, MILLISECONDS));
441      }
442  
443 <    public void testTimedPoll() {
444 <        try {
445 <            ArrayBlockingQueue q = populatedQueue(SIZE);
446 <            for (int i = 0; i < SIZE; ++i) {
447 <                assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
448 <            }
449 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
401 <        } catch (InterruptedException e){
402 <            fail("Unexpected exception");
403 <        }  
404 <    }
405 <
406 <    public void testInterruptedTimedPoll(){
407 <        Thread t = new Thread(new Runnable() {
408 <                public void run() {
409 <                    try {
410 <                        ArrayBlockingQueue q = populatedQueue(SIZE);
411 <                        for (int i = 0; i < SIZE; ++i) {
412 <                            threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
413 <                        }
414 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
415 <                    } catch (InterruptedException success){
416 <                    }  
417 <                }});
418 <        try {
419 <            t.start();
420 <            Thread.sleep(SHORT_DELAY_MS);
421 <            t.interrupt();
422 <            t.join();
423 <        }
424 <        catch (InterruptedException ie) {
425 <            fail("Unexpected exception");
443 >    /**
444 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
445 >     */
446 >    public void testTimedPoll() throws InterruptedException {
447 >        ArrayBlockingQueue q = populatedQueue(SIZE);
448 >        for (int i = 0; i < SIZE; ++i) {
449 >            assertEquals(i, q.poll(SHORT_DELAY_MS, MILLISECONDS));
450          }
451 +        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
452      }
453  
454 <    public void testTimedPollWithOffer(){
455 <        final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
456 <        Thread t = new Thread(new Runnable() {
457 <                public void run(){
458 <                    try {
459 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
460 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
461 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
462 <                        threadFail("Should block");
463 <                    } catch (InterruptedException success) { }                
454 >    /**
455 >     * Interrupted timed poll throws InterruptedException instead of
456 >     * returning timeout status
457 >     */
458 >    public void testInterruptedTimedPoll() throws InterruptedException {
459 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
460 >        final CountDownLatch aboutToWait = new CountDownLatch(1);
461 >        Thread t = newStartedThread(new CheckedRunnable() {
462 >            public void realRun() throws InterruptedException {
463 >                for (int i = 0; i < SIZE; ++i) {
464 >                    long t0 = System.nanoTime();
465 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
466 >                    assertTrue(millisElapsedSince(t0) < SMALL_DELAY_MS);
467                  }
468 <            });
469 <        try {
470 <            t.start();
471 <            Thread.sleep(SMALL_DELAY_MS);
472 <            assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
473 <            t.interrupt();
474 <            t.join();
475 <        } catch (Exception e){
476 <            fail("Unexpected exception");
477 <        }
478 <    }  
479 <
468 >                long t0 = System.nanoTime();
469 >                aboutToWait.countDown();
470 >                try {
471 >                    q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
472 >                    shouldThrow();
473 >                } catch (InterruptedException success) {
474 >                    assertTrue(millisElapsedSince(t0) < MEDIUM_DELAY_MS);
475 >                }
476 >            }});
477 >
478 >        aboutToWait.await();
479 >        waitForThreadToEnterWaitState(t, SMALL_DELAY_MS);
480 >        t.interrupt();
481 >        awaitTermination(t, MEDIUM_DELAY_MS);
482 >        checkEmpty(q);
483 >    }
484  
485 <    public void testPeek(){
485 >    /**
486 >     * peek returns next element, or null if empty
487 >     */
488 >    public void testPeek() {
489          ArrayBlockingQueue q = populatedQueue(SIZE);
490          for (int i = 0; i < SIZE; ++i) {
491 <            assertEquals(i, ((Integer)q.peek()).intValue());
492 <            q.poll();
491 >            assertEquals(i, q.peek());
492 >            assertEquals(i, q.poll());
493              assertTrue(q.peek() == null ||
494 <                       i != ((Integer)q.peek()).intValue());
494 >                       !q.peek().equals(i));
495          }
496 <        assertNull(q.peek());
496 >        assertNull(q.peek());
497      }
498  
499 <    public void testElement(){
499 >    /**
500 >     * element returns next element, or throws NSEE if empty
501 >     */
502 >    public void testElement() {
503          ArrayBlockingQueue q = populatedQueue(SIZE);
504          for (int i = 0; i < SIZE; ++i) {
505 <            assertEquals(i, ((Integer)q.element()).intValue());
506 <            q.poll();
505 >            assertEquals(i, q.element());
506 >            assertEquals(i, q.poll());
507          }
508          try {
509              q.element();
510 <            fail("no such element");
511 <        }
474 <        catch (NoSuchElementException success) {}
510 >            shouldThrow();
511 >        } catch (NoSuchElementException success) {}
512      }
513  
514 <    public void testRemove(){
514 >    /**
515 >     * remove removes next element, or throws NSEE if empty
516 >     */
517 >    public void testRemove() {
518          ArrayBlockingQueue q = populatedQueue(SIZE);
519          for (int i = 0; i < SIZE; ++i) {
520 <            assertEquals(i, ((Integer)q.remove()).intValue());
520 >            assertEquals(i, q.remove());
521          }
522          try {
523              q.remove();
524 <            fail("remove should throw");
525 <        } catch (NoSuchElementException success){
486 <        }  
524 >            shouldThrow();
525 >        } catch (NoSuchElementException success) {}
526      }
527  
528 <    public void testRemoveElement(){
528 >    /**
529 >     * remove(x) removes x and returns true if present
530 >     */
531 >    public void testRemoveElement() {
532          ArrayBlockingQueue q = populatedQueue(SIZE);
533          for (int i = 1; i < SIZE; i+=2) {
534              assertTrue(q.remove(new Integer(i)));
# Line 497 | Line 539 | public class ArrayBlockingQueueTest exte
539          }
540          assertTrue(q.isEmpty());
541      }
542 <        
543 <    public void testContains(){
542 >
543 >    /**
544 >     * contains(x) reports true when elements added but not yet removed
545 >     */
546 >    public void testContains() {
547          ArrayBlockingQueue q = populatedQueue(SIZE);
548          for (int i = 0; i < SIZE; ++i) {
549              assertTrue(q.contains(new Integer(i)));
550 <            q.poll();
550 >            assertEquals(i, q.poll());
551              assertFalse(q.contains(new Integer(i)));
552          }
553      }
554  
555 <    public void testClear(){
555 >    /**
556 >     * clear removes all elements
557 >     */
558 >    public void testClear() {
559          ArrayBlockingQueue q = populatedQueue(SIZE);
560          q.clear();
561          assertTrue(q.isEmpty());
# Line 515 | Line 563 | public class ArrayBlockingQueueTest exte
563          assertEquals(SIZE, q.remainingCapacity());
564          q.add(one);
565          assertFalse(q.isEmpty());
566 +        assertTrue(q.contains(one));
567          q.clear();
568          assertTrue(q.isEmpty());
569      }
570  
571 <    public void testContainsAll(){
571 >    /**
572 >     * containsAll(c) is true when c contains a subset of elements
573 >     */
574 >    public void testContainsAll() {
575          ArrayBlockingQueue q = populatedQueue(SIZE);
576          ArrayBlockingQueue p = new ArrayBlockingQueue(SIZE);
577          for (int i = 0; i < SIZE; ++i) {
# Line 530 | Line 582 | public class ArrayBlockingQueueTest exte
582          assertTrue(p.containsAll(q));
583      }
584  
585 <    public void testRetainAll(){
585 >    /**
586 >     * retainAll(c) retains only those elements of c and reports true if changed
587 >     */
588 >    public void testRetainAll() {
589          ArrayBlockingQueue q = populatedQueue(SIZE);
590          ArrayBlockingQueue p = populatedQueue(SIZE);
591          for (int i = 0; i < SIZE; ++i) {
# Line 546 | Line 601 | public class ArrayBlockingQueueTest exte
601          }
602      }
603  
604 <    public void testRemoveAll(){
604 >    /**
605 >     * removeAll(c) removes only those elements of c and reports true if changed
606 >     */
607 >    public void testRemoveAll() {
608          for (int i = 1; i < SIZE; ++i) {
609              ArrayBlockingQueue q = populatedQueue(SIZE);
610              ArrayBlockingQueue p = populatedQueue(i);
# Line 559 | Line 617 | public class ArrayBlockingQueueTest exte
617          }
618      }
619  
620 +    /**
621 +     * toArray contains all elements in FIFO order
622 +     */
623 +    public void testToArray() {
624 +        ArrayBlockingQueue q = populatedQueue(SIZE);
625 +        Object[] o = q.toArray();
626 +        for (int i = 0; i < o.length; i++)
627 +            assertSame(o[i], q.poll());
628 +    }
629 +
630 +    /**
631 +     * toArray(a) contains all elements in FIFO order
632 +     */
633 +    public void testToArray2() {
634 +        ArrayBlockingQueue<Integer> q = populatedQueue(SIZE);
635 +        Integer[] ints = new Integer[SIZE];
636 +        Integer[] array = q.toArray(ints);
637 +        assertSame(ints, array);
638 +        for (int i = 0; i < ints.length; i++)
639 +            assertSame(ints[i], q.poll());
640 +    }
641 +
642 +    /**
643 +     * toArray(null) throws NullPointerException
644 +     */
645 +    public void testToArray_NullArg() {
646 +        ArrayBlockingQueue q = populatedQueue(SIZE);
647 +        try {
648 +            q.toArray(null);
649 +            shouldThrow();
650 +        } catch (NullPointerException success) {}
651 +    }
652  
653 <    public void testToArray(){
653 >    /**
654 >     * toArray(incompatible array type) throws ArrayStoreException
655 >     */
656 >    public void testToArray1_BadArg() {
657          ArrayBlockingQueue q = populatedQueue(SIZE);
658 <        Object[] o = q.toArray();
659 <        try {
660 <        for(int i = 0; i < o.length; i++)
661 <            assertEquals(o[i], q.take());
569 <        } catch (InterruptedException e){
570 <            fail("Unexpected exception");
571 <        }    
572 <    }
573 <
574 <    public void testToArray2(){
575 <        ArrayBlockingQueue q = populatedQueue(SIZE);
576 <        Integer[] ints = new Integer[SIZE];
577 <        ints = (Integer[])q.toArray(ints);
578 <        try {
579 <            for(int i = 0; i < ints.length; i++)
580 <                assertEquals(ints[i], q.take());
581 <        } catch (InterruptedException e){
582 <            fail("Unexpected exception");
583 <        }    
584 <    }
585 <    
586 <    public void testIterator(){
587 <        ArrayBlockingQueue q = populatedQueue(SIZE);
588 <        Iterator it = q.iterator();
589 <        try {
590 <            while(it.hasNext()){
591 <                assertEquals(it.next(), q.take());
592 <            }
593 <        } catch (InterruptedException e){
594 <            fail("Unexpected exception");
595 <        }    
658 >        try {
659 >            q.toArray(new String[10]);
660 >            shouldThrow();
661 >        } catch (ArrayStoreException success) {}
662      }
663  
598    public void testIteratorOrdering() {
664  
665 +    /**
666 +     * iterator iterates through all elements
667 +     */
668 +    public void testIterator() throws InterruptedException {
669 +        ArrayBlockingQueue q = populatedQueue(SIZE);
670 +        Iterator it = q.iterator();
671 +        while (it.hasNext()) {
672 +            assertEquals(it.next(), q.take());
673 +        }
674 +    }
675 +
676 +    /**
677 +     * iterator.remove removes current element
678 +     */
679 +    public void testIteratorRemove() {
680          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
681 +        q.add(two);
682 +        q.add(one);
683 +        q.add(three);
684  
685 +        Iterator it = q.iterator();
686 +        it.next();
687 +        it.remove();
688 +
689 +        it = q.iterator();
690 +        assertSame(it.next(), one);
691 +        assertSame(it.next(), three);
692 +        assertFalse(it.hasNext());
693 +    }
694 +
695 +    /**
696 +     * iterator ordering is FIFO
697 +     */
698 +    public void testIteratorOrdering() {
699 +        final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
700          q.add(one);
701          q.add(two);
702          q.add(three);
# Line 607 | Line 705 | public class ArrayBlockingQueueTest exte
705  
706          int k = 0;
707          for (Iterator it = q.iterator(); it.hasNext();) {
708 <            int i = ((Integer)(it.next())).intValue();
611 <            assertEquals("items should come out in order", ++k, i);
708 >            assertEquals(++k, it.next());
709          }
710 <
614 <        assertEquals("should go through 3 elements", 3, k);
710 >        assertEquals(3, k);
711      }
712  
713 <    public void testWeaklyConsistentIteration () {
714 <
713 >    /**
714 >     * Modifications do not cause iterators to fail
715 >     */
716 >    public void testWeaklyConsistentIteration() {
717          final ArrayBlockingQueue q = new ArrayBlockingQueue(3);
620
718          q.add(one);
719          q.add(two);
720          q.add(three);
721 <
722 <        try {
723 <            for (Iterator it = q.iterator(); it.hasNext();) {
627 <                q.remove();
628 <                it.next();
629 <            }
630 <        }
631 <        catch (ConcurrentModificationException e) {
632 <            fail("weakly consistent iterator; should not get CME");
721 >        for (Iterator it = q.iterator(); it.hasNext();) {
722 >            q.remove();
723 >            it.next();
724          }
725 <
635 <        assertEquals("queue should be empty again", 0, q.size());
725 >        assertEquals(0, q.size());
726      }
727  
728  
729 <    public void testToString(){
729 >    /**
730 >     * toString contains toStrings of elements
731 >     */
732 >    public void testToString() {
733          ArrayBlockingQueue q = populatedQueue(SIZE);
734          String s = q.toString();
735          for (int i = 0; i < SIZE; ++i) {
736              assertTrue(s.indexOf(String.valueOf(i)) >= 0);
737          }
738 <    }        
738 >    }
739  
740  
741 +    /**
742 +     * offer transfers elements across Executor tasks
743 +     */
744      public void testOfferInExecutor() {
649
745          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
651
746          q.add(one);
747          q.add(two);
654
748          ExecutorService executor = Executors.newFixedThreadPool(2);
749 +        executor.execute(new CheckedRunnable() {
750 +            public void realRun() throws InterruptedException {
751 +                assertFalse(q.offer(three));
752 +                assertTrue(q.offer(three, MEDIUM_DELAY_MS, MILLISECONDS));
753 +                assertEquals(0, q.remainingCapacity());
754 +            }});
755 +
756 +        executor.execute(new CheckedRunnable() {
757 +            public void realRun() throws InterruptedException {
758 +                delay(SMALL_DELAY_MS);
759 +                assertSame(one, q.take());
760 +            }});
761  
657        executor.execute(new Runnable() {
658            public void run() {
659                threadAssertFalse(q.offer(three));
660                try {
661                    threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
662                    threadAssertEquals(0, q.remainingCapacity());
663                }
664                catch (InterruptedException e) {
665                    threadFail("should not be interrupted");
666                }
667            }
668        });
669
670        executor.execute(new Runnable() {
671            public void run() {
672                try {
673                    Thread.sleep(SMALL_DELAY_MS);
674                    threadAssertEquals(one, q.take());
675                }
676                catch (InterruptedException e) {
677                    threadFail("should not be interrupted");
678                }
679            }
680        });
681        
762          joinPool(executor);
683
763      }
764  
765 +    /**
766 +     * poll retrieves elements across Executor threads
767 +     */
768      public void testPollInExecutor() {
687
769          final ArrayBlockingQueue q = new ArrayBlockingQueue(2);
689
770          ExecutorService executor = Executors.newFixedThreadPool(2);
771 +        executor.execute(new CheckedRunnable() {
772 +            public void realRun() throws InterruptedException {
773 +                assertNull(q.poll());
774 +                assertSame(one, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
775 +                assertTrue(q.isEmpty());
776 +            }});
777 +
778 +        executor.execute(new CheckedRunnable() {
779 +            public void realRun() throws InterruptedException {
780 +                delay(SMALL_DELAY_MS);
781 +                q.put(one);
782 +            }});
783  
692        executor.execute(new Runnable() {
693            public void run() {
694                threadAssertNull(q.poll());
695                try {
696                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
697                    threadAssertTrue(q.isEmpty());
698                }
699                catch (InterruptedException e) {
700                    threadFail("should not be interrupted");
701                }
702            }
703        });
704
705        executor.execute(new Runnable() {
706            public void run() {
707                try {
708                    Thread.sleep(SMALL_DELAY_MS);
709                    q.put(one);
710                }
711                catch (InterruptedException e) {
712                    threadFail("should not be interrupted");
713                }
714            }
715        });
716        
784          joinPool(executor);
785 +    }
786 +
787 +    /**
788 +     * A deserialized serialized queue has same elements in same order
789 +     */
790 +    public void testSerialization() throws Exception {
791 +        ArrayBlockingQueue q = populatedQueue(SIZE);
792  
793 +        ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
794 +        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
795 +        out.writeObject(q);
796 +        out.close();
797 +
798 +        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
799 +        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
800 +        ArrayBlockingQueue r = (ArrayBlockingQueue)in.readObject();
801 +        assertEquals(q.size(), r.size());
802 +        while (!q.isEmpty())
803 +            assertEquals(q.remove(), r.remove());
804      }
805  
806 <    public void testSerialization() {
806 >    /**
807 >     * drainTo(null) throws NPE
808 >     */
809 >    public void testDrainToNull() {
810          ArrayBlockingQueue q = populatedQueue(SIZE);
811 +        try {
812 +            q.drainTo(null);
813 +            shouldThrow();
814 +        } catch (NullPointerException success) {}
815 +    }
816  
817 +    /**
818 +     * drainTo(this) throws IAE
819 +     */
820 +    public void testDrainToSelf() {
821 +        ArrayBlockingQueue q = populatedQueue(SIZE);
822          try {
823 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
824 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
825 <            out.writeObject(q);
728 <            out.close();
729 <
730 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
731 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
732 <            ArrayBlockingQueue r = (ArrayBlockingQueue)in.readObject();
733 <            assertEquals(q.size(), r.size());
734 <            while (!q.isEmpty())
735 <                assertEquals(q.remove(), r.remove());
736 <        } catch(Exception e){
737 <            fail("unexpected exception");
738 <        }
823 >            q.drainTo(q);
824 >            shouldThrow();
825 >        } catch (IllegalArgumentException success) {}
826      }
827  
828 +    /**
829 +     * drainTo(c) empties queue into another collection c
830 +     */
831 +    public void testDrainTo() {
832 +        ArrayBlockingQueue q = populatedQueue(SIZE);
833 +        ArrayList l = new ArrayList();
834 +        q.drainTo(l);
835 +        assertEquals(q.size(), 0);
836 +        assertEquals(l.size(), SIZE);
837 +        for (int i = 0; i < SIZE; ++i)
838 +            assertEquals(l.get(i), new Integer(i));
839 +        q.add(zero);
840 +        q.add(one);
841 +        assertFalse(q.isEmpty());
842 +        assertTrue(q.contains(zero));
843 +        assertTrue(q.contains(one));
844 +        l.clear();
845 +        q.drainTo(l);
846 +        assertEquals(q.size(), 0);
847 +        assertEquals(l.size(), 2);
848 +        for (int i = 0; i < 2; ++i)
849 +            assertEquals(l.get(i), new Integer(i));
850 +    }
851 +
852 +    /**
853 +     * drainTo empties full queue, unblocking a waiting put.
854 +     */
855 +    public void testDrainToWithActivePut() throws InterruptedException {
856 +        final ArrayBlockingQueue q = populatedQueue(SIZE);
857 +        Thread t = new Thread(new CheckedRunnable() {
858 +            public void realRun() throws InterruptedException {
859 +                q.put(new Integer(SIZE+1));
860 +            }});
861 +
862 +        t.start();
863 +        ArrayList l = new ArrayList();
864 +        q.drainTo(l);
865 +        assertTrue(l.size() >= SIZE);
866 +        for (int i = 0; i < SIZE; ++i)
867 +            assertEquals(l.get(i), new Integer(i));
868 +        t.join();
869 +        assertTrue(q.size() + l.size() >= SIZE);
870 +    }
871 +
872 +    /**
873 +     * drainTo(null, n) throws NPE
874 +     */
875 +    public void testDrainToNullN() {
876 +        ArrayBlockingQueue q = populatedQueue(SIZE);
877 +        try {
878 +            q.drainTo(null, 0);
879 +            shouldThrow();
880 +        } catch (NullPointerException success) {}
881 +    }
882 +
883 +    /**
884 +     * drainTo(this, n) throws IAE
885 +     */
886 +    public void testDrainToSelfN() {
887 +        ArrayBlockingQueue q = populatedQueue(SIZE);
888 +        try {
889 +            q.drainTo(q, 0);
890 +            shouldThrow();
891 +        } catch (IllegalArgumentException success) {}
892 +    }
893 +
894 +    /**
895 +     * drainTo(c, n) empties first min(n, size) elements of queue into c
896 +     */
897 +    public void testDrainToN() {
898 +        ArrayBlockingQueue q = new ArrayBlockingQueue(SIZE*2);
899 +        for (int i = 0; i < SIZE + 2; ++i) {
900 +            for (int j = 0; j < SIZE; j++)
901 +                assertTrue(q.offer(new Integer(j)));
902 +            ArrayList l = new ArrayList();
903 +            q.drainTo(l, i);
904 +            int k = (i < SIZE) ? i : SIZE;
905 +            assertEquals(l.size(), k);
906 +            assertEquals(q.size(), SIZE-k);
907 +            for (int j = 0; j < k; ++j)
908 +                assertEquals(l.get(j), new Integer(j));
909 +            while (q.poll() != null) ;
910 +        }
911 +    }
912  
913   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines