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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines