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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines