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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines