ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/LinkedBlockingQueueTest.java
(Generate patch)

Comparing jsr166/src/test/tck/LinkedBlockingQueueTest.java (file contents):
Revision 1.16 by jsr166, Sat Nov 21 02:33:20 2009 UTC vs.
Revision 1.84 by jsr166, Wed Jan 27 02:55:18 2021 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines