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

Comparing jsr166/src/test/tck/LinkedTransferQueueTest.java (file contents):
Revision 1.4 by jsr166, Sat Aug 1 22:09:13 2009 UTC vs.
Revision 1.71 by jsr166, Sat Mar 18 20:42:20 2017 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 John Vint
6   */
7  
8 < import java.io.BufferedInputStream;
9 < import java.io.BufferedOutputStream;
10 < import java.io.ByteArrayInputStream;
11 < import java.io.ByteArrayOutputStream;
12 < import java.io.ObjectInputStream;
13 < import java.io.ObjectOutputStream;
8 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
9 >
10   import java.util.ArrayList;
11   import java.util.Arrays;
12 < import java.util.ConcurrentModificationException;
12 > import java.util.Collection;
13   import java.util.Iterator;
14 + import java.util.List;
15   import java.util.NoSuchElementException;
16 < import java.util.concurrent.*;
16 > import java.util.Queue;
17 > import java.util.concurrent.BlockingQueue;
18 > import java.util.concurrent.Callable;
19 > import java.util.concurrent.CountDownLatch;
20 > import java.util.concurrent.Executors;
21 > import java.util.concurrent.ExecutorService;
22 > import java.util.concurrent.LinkedTransferQueue;
23 >
24   import junit.framework.Test;
21 import junit.framework.TestSuite;
25  
26 + @SuppressWarnings({"unchecked", "rawtypes"})
27   public class LinkedTransferQueueTest extends JSR166TestCase {
28 +    public static class Generic extends BlockingQueueTest {
29 +        protected BlockingQueue emptyCollection() {
30 +            return new LinkedTransferQueue();
31 +        }
32 +    }
33  
34      public static void main(String[] args) {
35 <        junit.textui.TestRunner.run(suite());
35 >        main(suite(), args);
36      }
37  
38      public static Test suite() {
39 <        return new TestSuite(LinkedTransferQueueTest.class);
39 >        class Implementation implements CollectionImplementation {
40 >            public Class<?> klazz() { return LinkedTransferQueue.class; }
41 >            public Collection emptyCollection() { return new LinkedTransferQueue(); }
42 >            public Object makeElement(int i) { return i; }
43 >            public boolean isConcurrent() { return true; }
44 >            public boolean permitsNulls() { return false; }
45 >        }
46 >        return newTestSuite(LinkedTransferQueueTest.class,
47 >                            new Generic().testSuite(),
48 >                            CollectionTest.testSuite(new Implementation()));
49      }
50  
51      /**
52 <     * Constructor builds new queue with size being zero and empty being true
52 >     * Constructor builds new queue with size being zero and empty
53 >     * being true
54       */
55      public void testConstructor1() {
56          assertEquals(0, new LinkedTransferQueue().size());
# Line 39 | Line 58 | public class LinkedTransferQueueTest ext
58      }
59  
60      /**
61 <     * Initializing constructor with null collection throws NPE
61 >     * Initializing constructor with null collection throws
62 >     * NullPointerException
63       */
64      public void testConstructor2() {
65          try {
66              new LinkedTransferQueue(null);
67              shouldThrow();
68 <        } catch (NullPointerException success) {
49 <        }
68 >        } catch (NullPointerException success) {}
69      }
70  
71      /**
72 <     * Initializing from Collection of null elements throws NPE
72 >     * Initializing from Collection of null elements throws
73 >     * NullPointerException
74       */
75      public void testConstructor3() {
76 +        Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
77          try {
78 <            Integer[] ints = new Integer[SIZE];
58 <            LinkedTransferQueue q = new LinkedTransferQueue(Arrays.asList(ints));
78 >            new LinkedTransferQueue(elements);
79              shouldThrow();
80 <        } catch (NullPointerException success) {
61 <        }
80 >        } catch (NullPointerException success) {}
81      }
82  
83      /**
84       * Initializing constructor with a collection containing some null elements
85 <     * throws NPE
85 >     * throws NullPointerException
86       */
87      public void testConstructor4() {
88 +        Integer[] ints = new Integer[SIZE];
89 +        for (int i = 0; i < SIZE - 1; ++i)
90 +            ints[i] = i;
91 +        Collection<Integer> elements = Arrays.asList(ints);
92          try {
93 <            Integer[] ints = new Integer[SIZE];
71 <            for (int i = 0; i < SIZE - 1; ++i) {
72 <                ints[i] = new Integer(i);
73 <            }
74 <            LinkedTransferQueue q = new LinkedTransferQueue(Arrays.asList(ints));
93 >            new LinkedTransferQueue(elements);
94              shouldThrow();
95 <        } catch (NullPointerException success) {
77 <        }
95 >        } catch (NullPointerException success) {}
96      }
97  
98      /**
99       * Queue contains all elements of the collection it is initialized by
100       */
101      public void testConstructor5() {
102 <        try {
103 <            Integer[] ints = new Integer[SIZE];
104 <            for (int i = 0; i < SIZE; ++i) {
105 <                ints[i] = new Integer(i);
106 <            }
107 <            LinkedTransferQueue q = new LinkedTransferQueue(Arrays.asList(ints));
108 <            for (int i = 0; i < SIZE; ++i) {
109 <                assertEquals(ints[i], q.poll());
110 <            }
111 <        } finally {
102 >        Integer[] ints = new Integer[SIZE];
103 >        for (int i = 0; i < SIZE; ++i) {
104 >            ints[i] = i;
105 >        }
106 >        List intList = Arrays.asList(ints);
107 >        LinkedTransferQueue q
108 >            = new LinkedTransferQueue(intList);
109 >        assertEquals(q.size(), intList.size());
110 >        assertEquals(q.toString(), intList.toString());
111 >        assertTrue(Arrays.equals(q.toArray(),
112 >                                     intList.toArray()));
113 >        assertTrue(Arrays.equals(q.toArray(new Object[0]),
114 >                                 intList.toArray(new Object[0])));
115 >        assertTrue(Arrays.equals(q.toArray(new Object[SIZE]),
116 >                                 intList.toArray(new Object[SIZE])));
117 >        for (int i = 0; i < SIZE; ++i) {
118 >            assertEquals(ints[i], q.poll());
119          }
120      }
121  
122      /**
123 <     * Remaining capacity never decrease nor increase on add or remove
123 >     * remainingCapacity() always returns Integer.MAX_VALUE
124       */
125      public void testRemainingCapacity() {
126 <        LinkedTransferQueue q = populatedQueue(SIZE);
102 <        int remainingCapacity = q.remainingCapacity();
126 >        BlockingQueue q = populatedQueue(SIZE);
127          for (int i = 0; i < SIZE; ++i) {
128 <            assertEquals(remainingCapacity, q.remainingCapacity());
128 >            assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
129              assertEquals(SIZE - i, q.size());
130 <            q.remove();
130 >            assertEquals(i, q.remove());
131          }
132          for (int i = 0; i < SIZE; ++i) {
133 <            assertEquals(remainingCapacity, q.remainingCapacity());
133 >            assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
134              assertEquals(i, q.size());
135 <            q.add(new Integer(i));
112 <        }
113 <    }
114 <
115 <    /**
116 <     * offer(null) throws NPE
117 <     */
118 <    public void testOfferNull() {
119 <        try {
120 <            LinkedTransferQueue q = new LinkedTransferQueue();
121 <            q.offer(null);
122 <            shouldThrow();
123 <        } catch (NullPointerException success) {
135 >            assertTrue(q.add(i));
136          }
137      }
138  
139      /**
140 <     * add(null) throws NPE
129 <     */
130 <    public void testAddNull() {
131 <        try {
132 <            LinkedTransferQueue q = new LinkedTransferQueue();
133 <            q.add(null);
134 <            shouldThrow();
135 <        } catch (NullPointerException success) {
136 <        }
137 <    }
138 <
139 <    /**
140 <     * addAll(null) throws NPE
141 <     */
142 <    public void testAddAll1() {
143 <        try {
144 <            LinkedTransferQueue q = new LinkedTransferQueue();
145 <            q.addAll(null);
146 <            shouldThrow();
147 <        } catch (NullPointerException success) {
148 <        }
149 <    }
150 <
151 <    /**
152 <     * addAll(this) throws IAE
140 >     * addAll(this) throws IllegalArgumentException
141       */
142      public void testAddAllSelf() {
143 +        LinkedTransferQueue q = populatedQueue(SIZE);
144          try {
156            LinkedTransferQueue q = populatedQueue(SIZE);
145              q.addAll(q);
146              shouldThrow();
147 <        } catch (IllegalArgumentException success) {
160 <        }
147 >        } catch (IllegalArgumentException success) {}
148      }
149  
150      /**
151 <     * addAll of a collection with null elements throws NPE
152 <     */
166 <    public void testAddAll2() {
167 <        try {
168 <            LinkedTransferQueue q = new LinkedTransferQueue();
169 <            Integer[] ints = new Integer[SIZE];
170 <            q.addAll(Arrays.asList(ints));
171 <            shouldThrow();
172 <        } catch (NullPointerException success) {
173 <        }
174 <    }
175 <
176 <    /**
177 <     * addAll of a collection with any null elements throws NPE after
178 <     * possibly adding some elements
151 >     * addAll of a collection with any null elements throws
152 >     * NullPointerException after possibly adding some elements
153       */
154      public void testAddAll3() {
155 +        LinkedTransferQueue q = new LinkedTransferQueue();
156 +        Integer[] ints = new Integer[SIZE];
157 +        for (int i = 0; i < SIZE - 1; ++i)
158 +            ints[i] = i;
159          try {
182            LinkedTransferQueue q = new LinkedTransferQueue();
183            Integer[] ints = new Integer[SIZE];
184            for (int i = 0; i < SIZE - 1; ++i) {
185                ints[i] = new Integer(i);
186            }
160              q.addAll(Arrays.asList(ints));
161              shouldThrow();
162 <        } catch (NullPointerException success) {
190 <        }
162 >        } catch (NullPointerException success) {}
163      }
164  
165      /**
166       * Queue contains all elements, in traversal order, of successful addAll
167       */
168      public void testAddAll5() {
169 <        try {
170 <            Integer[] empty = new Integer[0];
171 <            Integer[] ints = new Integer[SIZE];
172 <            for (int i = 0; i < SIZE; ++i) {
201 <                ints[i] = new Integer(i);
202 <            }
203 <            LinkedTransferQueue q = new LinkedTransferQueue();
204 <            assertFalse(q.addAll(Arrays.asList(empty)));
205 <            assertTrue(q.addAll(Arrays.asList(ints)));
206 <            for (int i = 0; i < SIZE; ++i) {
207 <                assertEquals(ints[i], q.poll());
208 <            }
209 <        } finally {
169 >        Integer[] empty = new Integer[0];
170 >        Integer[] ints = new Integer[SIZE];
171 >        for (int i = 0; i < SIZE; ++i) {
172 >            ints[i] = i;
173          }
174 <    }
175 <
176 <    /**
177 <     * put(null) throws NPE
178 <     */
216 <    public void testPutNull() {
217 <        try {
218 <            LinkedTransferQueue q = new LinkedTransferQueue();
219 <            q.put(null);
220 <            shouldThrow();
221 <        } catch (NullPointerException success) {
222 <        } catch (Exception ie) {
223 <            unexpectedException();
174 >        LinkedTransferQueue q = new LinkedTransferQueue();
175 >        assertFalse(q.addAll(Arrays.asList(empty)));
176 >        assertTrue(q.addAll(Arrays.asList(ints)));
177 >        for (int i = 0; i < SIZE; ++i) {
178 >            assertEquals(ints[i], q.poll());
179          }
180      }
181  
# Line 228 | Line 183 | public class LinkedTransferQueueTest ext
183       * all elements successfully put are contained
184       */
185      public void testPut() {
186 <        try {
187 <            LinkedTransferQueue q = new LinkedTransferQueue();
188 <            for (int i = 0; i < SIZE; ++i) {
189 <                Integer I = new Integer(i);
190 <                q.put(I);
236 <                assertTrue(q.contains(I));
237 <            }
238 <        } catch (Exception ie) {
239 <            unexpectedException();
186 >        LinkedTransferQueue<Integer> q = new LinkedTransferQueue<>();
187 >        for (int i = 0; i < SIZE; ++i) {
188 >            assertEquals(i, q.size());
189 >            q.put(i);
190 >            assertTrue(q.contains(i));
191          }
192      }
193  
194      /**
195       * take retrieves elements in FIFO order
196       */
197 <    public void testTake() {
198 <        try {
199 <            LinkedTransferQueue q = populatedQueue(SIZE);
200 <            for (int i = 0; i < SIZE; ++i) {
250 <                assertEquals(i, ((Integer) q.take()).intValue());
251 <            }
252 <        } catch (InterruptedException e) {
253 <            unexpectedException();
197 >    public void testTake() throws InterruptedException {
198 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
199 >        for (int i = 0; i < SIZE; ++i) {
200 >            assertEquals(i, (int) q.take());
201          }
202      }
203  
204      /**
205 <     * take blocks interruptibly when empty
205 >     * take removes existing elements until empty, then blocks interruptibly
206       */
207 <    public void testTakeFromEmpty() {
208 <        final LinkedTransferQueue q = new LinkedTransferQueue();
209 <        Thread t = new Thread(new Runnable() {
207 >    public void testBlockingTake() throws InterruptedException {
208 >        final BlockingQueue q = populatedQueue(SIZE);
209 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
210 >        Thread t = newStartedThread(new CheckedRunnable() {
211 >            public void realRun() throws InterruptedException {
212 >                for (int i = 0; i < SIZE; ++i) {
213 >                    assertEquals(i, q.take());
214 >                }
215  
216 <            public void run() {
216 >                Thread.currentThread().interrupt();
217                  try {
218                      q.take();
219 <                    threadShouldThrow();
220 <                } catch (InterruptedException success) {
221 <                }
270 <            }
271 <        });
272 <        try {
273 <            t.start();
274 <            Thread.sleep(SHORT_DELAY_MS);
275 <            t.interrupt();
276 <            t.join();
277 <        } catch (Exception e) {
278 <            unexpectedException();
279 <        }
280 <    }
281 <
282 <    /**
283 <     * Take removes existing elements until empty, then blocks interruptibly
284 <     */
285 <    public void testBlockingTake() {
286 <        Thread t = new Thread(new Runnable() {
219 >                    shouldThrow();
220 >                } catch (InterruptedException success) {}
221 >                assertFalse(Thread.interrupted());
222  
223 <            public void run() {
223 >                pleaseInterrupt.countDown();
224                  try {
290                    LinkedTransferQueue q = populatedQueue(SIZE);
291                    for (int i = 0; i < SIZE; ++i) {
292                        assertEquals(i, ((Integer) q.take()).intValue());
293                    }
225                      q.take();
226 <                    threadShouldThrow();
227 <                } catch (InterruptedException success) {
228 <                }
229 <            }
230 <        });
231 <        t.start();
232 <        try {
233 <            Thread.sleep(SHORT_DELAY_MS);
234 <            t.interrupt();
304 <            t.join();
305 <        } catch (InterruptedException ie) {
306 <            unexpectedException();
307 <        }
226 >                    shouldThrow();
227 >                } catch (InterruptedException success) {}
228 >                assertFalse(Thread.interrupted());
229 >            }});
230 >
231 >        await(pleaseInterrupt);
232 >        assertThreadStaysAlive(t);
233 >        t.interrupt();
234 >        awaitTermination(t);
235      }
236  
237      /**
238       * poll succeeds unless empty
239       */
240 <    public void testPoll() {
241 <        LinkedTransferQueue q = populatedQueue(SIZE);
240 >    public void testPoll() throws InterruptedException {
241 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
242          for (int i = 0; i < SIZE; ++i) {
243 <            assertEquals(i, ((Integer) q.poll()).intValue());
243 >            assertEquals(i, (int) q.poll());
244          }
245          assertNull(q.poll());
246 +        checkEmpty(q);
247      }
248  
249      /**
250 <     * timed pool with zero timeout succeeds when non-empty, else times out
250 >     * timed poll with zero timeout succeeds when non-empty, else times out
251       */
252 <    public void testTimedPoll0() {
253 <        try {
254 <            LinkedTransferQueue q = populatedQueue(SIZE);
255 <            for (int i = 0; i < SIZE; ++i) {
328 <                assertEquals(i, ((Integer) q.poll(0, TimeUnit.MILLISECONDS)).intValue());
329 <            }
330 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
331 <        } catch (InterruptedException e) {
332 <            unexpectedException();
252 >    public void testTimedPoll0() throws InterruptedException {
253 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
254 >        for (int i = 0; i < SIZE; ++i) {
255 >            assertEquals(i, (int) q.poll(0, MILLISECONDS));
256          }
257 +        assertNull(q.poll(0, MILLISECONDS));
258 +        checkEmpty(q);
259      }
260  
261      /**
262 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
262 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
263       */
264 <    public void testTimedPoll() {
265 <        try {
266 <            LinkedTransferQueue q = populatedQueue(SIZE);
267 <            for (int i = 0; i < SIZE; ++i) {
268 <                assertEquals(i, ((Integer) q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
269 <            }
270 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
271 <        } catch (InterruptedException e) {
272 <            unexpectedException();
273 <        }
264 >    public void testTimedPoll() throws InterruptedException {
265 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
266 >        long startTime = System.nanoTime();
267 >        for (int i = 0; i < SIZE; ++i)
268 >            assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
269 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
270 >
271 >        startTime = System.nanoTime();
272 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
273 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
274 >        checkEmpty(q);
275      }
276  
277      /**
278       * Interrupted timed poll throws InterruptedException instead of
279       * returning timeout status
280       */
281 <    public void testInterruptedTimedPoll() {
282 <        Thread t = new Thread(new Runnable() {
283 <
284 <            public void run() {
281 >    public void testInterruptedTimedPoll() throws InterruptedException {
282 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
283 >        final CountDownLatch aboutToWait = new CountDownLatch(1);
284 >        Thread t = newStartedThread(new CheckedRunnable() {
285 >            public void realRun() throws InterruptedException {
286 >                long startTime = System.nanoTime();
287 >                for (int i = 0; i < SIZE; ++i)
288 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
289 >                aboutToWait.countDown();
290                  try {
291 <                    LinkedTransferQueue q = populatedQueue(SIZE);
292 <                    for (int i = 0; i < SIZE; ++i) {
293 <                        threadAssertEquals(i, ((Integer) q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
294 <                    }
295 <                    threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
296 <                } catch (InterruptedException success) {
297 <                }
298 <            }
299 <        });
300 <        t.start();
301 <        try {
371 <            Thread.sleep(SHORT_DELAY_MS);
372 <            t.interrupt();
373 <            t.join();
374 <        } catch (InterruptedException ie) {
375 <            unexpectedException();
376 <        }
291 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
292 >                    shouldThrow();
293 >                } catch (InterruptedException success) {}
294 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
295 >            }});
296 >
297 >        aboutToWait.await();
298 >        waitForThreadToEnterWaitState(t);
299 >        t.interrupt();
300 >        awaitTermination(t);
301 >        checkEmpty(q);
302      }
303  
304      /**
305 <     * timed poll before a delayed offer fails; after offer succeeds;
306 <     * on interruption throws
307 <     */
308 <    public void testTimedPollWithOffer() {
309 <        final LinkedTransferQueue q = new LinkedTransferQueue();
310 <        Thread t = new Thread(new Runnable() {
311 <
312 <            public void run() {
305 >     * timed poll after thread interrupted throws InterruptedException
306 >     * instead of returning timeout status
307 >     */
308 >    public void testTimedPollAfterInterrupt() throws InterruptedException {
309 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
310 >        Thread t = newStartedThread(new CheckedRunnable() {
311 >            public void realRun() throws InterruptedException {
312 >                long startTime = System.nanoTime();
313 >                Thread.currentThread().interrupt();
314 >                for (int i = 0; i < SIZE; ++i)
315 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
316                  try {
317 <                    threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
318 <                    q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
319 <                    q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
320 <                    threadShouldThrow();
321 <                } catch (InterruptedException success) {
322 <                }
323 <            }
324 <        });
397 <        try {
398 <            t.start();
399 <            Thread.sleep(SMALL_DELAY_MS);
400 <            assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
401 <            t.interrupt();
402 <            t.join();
403 <        } catch (Exception e) {
404 <            unexpectedException();
405 <        }
317 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
318 >                    shouldThrow();
319 >                } catch (InterruptedException success) {}
320 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
321 >            }});
322 >
323 >        awaitTermination(t);
324 >        checkEmpty(q);
325      }
326  
327      /**
328       * peek returns next element, or null if empty
329       */
330 <    public void testPeek() {
331 <        LinkedTransferQueue q = populatedQueue(SIZE);
330 >    public void testPeek() throws InterruptedException {
331 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
332          for (int i = 0; i < SIZE; ++i) {
333 <            assertEquals(i, ((Integer) q.peek()).intValue());
334 <            q.poll();
333 >            assertEquals(i, (int) q.peek());
334 >            assertEquals(i, (int) q.poll());
335              assertTrue(q.peek() == null ||
336 <                    i != ((Integer) q.peek()).intValue());
336 >                       i != (int) q.peek());
337          }
338          assertNull(q.peek());
339 +        checkEmpty(q);
340      }
341  
342      /**
343 <     * element returns next element, or throws NSEE if empty
343 >     * element returns next element, or throws NoSuchElementException if empty
344       */
345 <    public void testElement() {
346 <        LinkedTransferQueue q = populatedQueue(SIZE);
345 >    public void testElement() throws InterruptedException {
346 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
347          for (int i = 0; i < SIZE; ++i) {
348 <            assertEquals(i, ((Integer) q.element()).intValue());
349 <            q.poll();
348 >            assertEquals(i, (int) q.element());
349 >            assertEquals(i, (int) q.poll());
350          }
351          try {
352              q.element();
353              shouldThrow();
354 <        } catch (NoSuchElementException success) {
355 <        }
354 >        } catch (NoSuchElementException success) {}
355 >        checkEmpty(q);
356      }
357  
358      /**
359 <     * remove removes next element, or throws NSEE if empty
359 >     * remove removes next element, or throws NoSuchElementException if empty
360       */
361 <    public void testRemove() {
362 <        LinkedTransferQueue q = populatedQueue(SIZE);
361 >    public void testRemove() throws InterruptedException {
362 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
363          for (int i = 0; i < SIZE; ++i) {
364 <            assertEquals(i, ((Integer) q.remove()).intValue());
364 >            assertEquals(i, (int) q.remove());
365          }
366          try {
367              q.remove();
368              shouldThrow();
369 <        } catch (NoSuchElementException success) {
370 <        }
451 <    }
452 <
453 <    /**
454 <     * remove(x) removes x and returns true if present
455 <     */
456 <    public void testRemoveElement() {
457 <        LinkedTransferQueue q = populatedQueue(SIZE);
458 <        for (int i = 1; i < SIZE; i += 2) {
459 <            assertTrue(q.remove(new Integer(i)));
460 <        }
461 <        for (int i = 0; i < SIZE; i += 2) {
462 <            assertTrue(q.remove(new Integer(i)));
463 <            assertFalse(q.remove(new Integer(i + 1)));
464 <        }
465 <        assertTrue(q.isEmpty());
369 >        } catch (NoSuchElementException success) {}
370 >        checkEmpty(q);
371      }
372  
373      /**
374       * An add following remove(x) succeeds
375       */
376 <    public void testRemoveElementAndAdd() {
377 <        try {
378 <            LinkedTransferQueue q = new LinkedTransferQueue();
379 <            assertTrue(q.add(new Integer(1)));
380 <            assertTrue(q.add(new Integer(2)));
381 <            assertTrue(q.remove(new Integer(1)));
382 <            assertTrue(q.remove(new Integer(2)));
383 <            assertTrue(q.add(new Integer(3)));
479 <            assertTrue(q.take() != null);
480 <        } catch (Exception e) {
481 <            unexpectedException();
482 <        }
376 >    public void testRemoveElementAndAdd() throws InterruptedException {
377 >        LinkedTransferQueue q = new LinkedTransferQueue();
378 >        assertTrue(q.add(one));
379 >        assertTrue(q.add(two));
380 >        assertTrue(q.remove(one));
381 >        assertTrue(q.remove(two));
382 >        assertTrue(q.add(three));
383 >        assertSame(q.take(), three);
384      }
385  
386      /**
387       * contains(x) reports true when elements added but not yet removed
388       */
389      public void testContains() {
390 <        LinkedTransferQueue q = populatedQueue(SIZE);
390 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
391          for (int i = 0; i < SIZE; ++i) {
392 <            assertTrue(q.contains(new Integer(i)));
393 <            q.poll();
394 <            assertFalse(q.contains(new Integer(i)));
392 >            assertTrue(q.contains(i));
393 >            assertEquals(i, (int) q.poll());
394 >            assertFalse(q.contains(i));
395          }
396      }
397  
398      /**
399       * clear removes all elements
400       */
401 <    public void testClear() {
401 >    public void testClear() throws InterruptedException {
402          LinkedTransferQueue q = populatedQueue(SIZE);
502        int remainingCapacity = q.remainingCapacity();
403          q.clear();
404 <        assertTrue(q.isEmpty());
405 <        assertEquals(0, q.size());
506 <        assertEquals(remainingCapacity, q.remainingCapacity());
404 >        checkEmpty(q);
405 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
406          q.add(one);
407          assertFalse(q.isEmpty());
408 +        assertEquals(1, q.size());
409          assertTrue(q.contains(one));
410          q.clear();
411 <        assertTrue(q.isEmpty());
411 >        checkEmpty(q);
412      }
413  
414      /**
415       * containsAll(c) is true when c contains a subset of elements
416       */
417      public void testContainsAll() {
418 <        LinkedTransferQueue q = populatedQueue(SIZE);
419 <        LinkedTransferQueue p = new LinkedTransferQueue();
418 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
419 >        LinkedTransferQueue<Integer> p = new LinkedTransferQueue<>();
420          for (int i = 0; i < SIZE; ++i) {
421              assertTrue(q.containsAll(p));
422              assertFalse(p.containsAll(q));
423 <            p.add(new Integer(i));
423 >            p.add(i);
424          }
425          assertTrue(p.containsAll(q));
426      }
427  
428      /**
429 <     * retainAll(c) retains only those elements of c and reports true if changed
429 >     * retainAll(c) retains only those elements of c and reports true
430 >     * if changed
431       */
432      public void testRetainAll() {
433          LinkedTransferQueue q = populatedQueue(SIZE);
# Line 545 | Line 446 | public class LinkedTransferQueueTest ext
446      }
447  
448      /**
449 <     * removeAll(c) removes only those elements of c and reports true if changed
449 >     * removeAll(c) removes only those elements of c and reports true
450 >     * if changed
451       */
452      public void testRemoveAll() {
453          for (int i = 1; i < SIZE; ++i) {
# Line 554 | Line 456 | public class LinkedTransferQueueTest ext
456              assertTrue(q.removeAll(p));
457              assertEquals(SIZE - i, q.size());
458              for (int j = 0; j < i; ++j) {
459 <                Integer I = (Integer) (p.remove());
558 <                assertFalse(q.contains(I));
459 >                assertFalse(q.contains(p.remove()));
460              }
461          }
462      }
463  
464      /**
465 <     * toArray contains all elements
465 >     * toArray() contains all elements in FIFO order
466       */
467      public void testToArray() {
468          LinkedTransferQueue q = populatedQueue(SIZE);
469          Object[] o = q.toArray();
470 <        try {
471 <            for (int i = 0; i < o.length; i++) {
571 <                assertEquals(o[i], q.take());
572 <            }
573 <        } catch (InterruptedException e) {
574 <            unexpectedException();
470 >        for (int i = 0; i < o.length; i++) {
471 >            assertSame(o[i], q.poll());
472          }
473      }
474  
475      /**
476 <     * toArray(a) contains all elements
476 >     * toArray(a) contains all elements in FIFO order
477       */
478      public void testToArray2() {
479 <        LinkedTransferQueue q = populatedQueue(SIZE);
479 >        LinkedTransferQueue<Integer> q = populatedQueue(SIZE);
480          Integer[] ints = new Integer[SIZE];
481 <        ints = (Integer[]) q.toArray(ints);
482 <        try {
483 <            for (int i = 0; i < ints.length; i++) {
484 <                assertEquals(ints[i], q.take());
588 <            }
589 <        } catch (InterruptedException e) {
590 <            unexpectedException();
591 <        }
592 <    }
593 <
594 <    /**
595 <     * toArray(null) throws NPE
596 <     */
597 <    public void testToArray_BadArg() {
598 <        try {
599 <            LinkedTransferQueue q = populatedQueue(SIZE);
600 <            Object o[] = q.toArray(null);
601 <            shouldThrow();
602 <        } catch (NullPointerException success) {
481 >        Integer[] array = q.toArray(ints);
482 >        assertSame(ints, array);
483 >        for (int i = 0; i < ints.length; i++) {
484 >            assertSame(ints[i], q.poll());
485          }
486      }
487  
488      /**
489 <     * toArray with incompatible array type throws CCE
489 >     * toArray(incompatible array type) throws ArrayStoreException
490       */
491      public void testToArray1_BadArg() {
492 +        LinkedTransferQueue q = populatedQueue(SIZE);
493          try {
494 <            LinkedTransferQueue q = populatedQueue(SIZE);
612 <            Object o[] = q.toArray(new String[10]);
494 >            q.toArray(new String[10]);
495              shouldThrow();
496 <        } catch (ArrayStoreException success) {
615 <        }
496 >        } catch (ArrayStoreException success) {}
497      }
498  
499      /**
500       * iterator iterates through all elements
501       */
502 <    public void testIterator() {
502 >    public void testIterator() throws InterruptedException {
503          LinkedTransferQueue q = populatedQueue(SIZE);
504          Iterator it = q.iterator();
505 <        try {
506 <            while (it.hasNext()) {
507 <                assertEquals(it.next(), q.take());
508 <            }
509 <        } catch (InterruptedException e) {
510 <            unexpectedException();
511 <        }
505 >        int i;
506 >        for (i = 0; it.hasNext(); i++)
507 >            assertTrue(q.contains(it.next()));
508 >        assertEquals(i, SIZE);
509 >        assertIteratorExhausted(it);
510 >
511 >        it = q.iterator();
512 >        for (i = 0; it.hasNext(); i++)
513 >            assertEquals(it.next(), q.take());
514 >        assertEquals(i, SIZE);
515 >        assertIteratorExhausted(it);
516      }
517  
518      /**
519 <     * iterator.remove removes current element
519 >     * iterator of empty collection has no elements
520 >     */
521 >    public void testEmptyIterator() {
522 >        assertIteratorExhausted(new LinkedTransferQueue().iterator());
523 >    }
524 >
525 >    /**
526 >     * iterator.remove() removes current element
527       */
528      public void testIteratorRemove() {
529          final LinkedTransferQueue q = new LinkedTransferQueue();
# Line 644 | Line 536 | public class LinkedTransferQueueTest ext
536          it.remove();
537  
538          it = q.iterator();
539 <        assertEquals(it.next(), one);
540 <        assertEquals(it.next(), three);
539 >        assertSame(it.next(), one);
540 >        assertSame(it.next(), three);
541          assertFalse(it.hasNext());
542      }
543  
# Line 653 | Line 545 | public class LinkedTransferQueueTest ext
545       * iterator ordering is FIFO
546       */
547      public void testIteratorOrdering() {
548 <        final LinkedTransferQueue q = new LinkedTransferQueue();
549 <        int remainingCapacity = q.remainingCapacity();
548 >        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<>();
549 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
550          q.add(one);
551          q.add(two);
552          q.add(three);
553 <        assertEquals(remainingCapacity, q.remainingCapacity());
553 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
554          int k = 0;
555 <        for (Iterator it = q.iterator(); it.hasNext();) {
556 <            int i = ((Integer) (it.next())).intValue();
665 <            assertEquals(++k, i);
555 >        for (Integer n : q) {
556 >            assertEquals(++k, (int) n);
557          }
558          assertEquals(3, k);
559      }
# Line 675 | Line 566 | public class LinkedTransferQueueTest ext
566          q.add(one);
567          q.add(two);
568          q.add(three);
569 <        try {
570 <            for (Iterator it = q.iterator(); it.hasNext();) {
571 <                q.remove();
681 <                it.next();
682 <            }
683 <        } catch (ConcurrentModificationException e) {
684 <            unexpectedException();
569 >        for (Iterator it = q.iterator(); it.hasNext();) {
570 >            q.remove();
571 >            it.next();
572          }
573          assertEquals(0, q.size());
574      }
# Line 693 | Line 580 | public class LinkedTransferQueueTest ext
580          LinkedTransferQueue q = populatedQueue(SIZE);
581          String s = q.toString();
582          for (int i = 0; i < SIZE; ++i) {
583 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
583 >            assertTrue(s.contains(String.valueOf(i)));
584          }
585      }
586  
# Line 702 | Line 589 | public class LinkedTransferQueueTest ext
589       */
590      public void testOfferInExecutor() {
591          final LinkedTransferQueue q = new LinkedTransferQueue();
592 <        q.add(one);
593 <        q.add(two);
594 <        ExecutorService executor = Executors.newFixedThreadPool(2);
708 <        executor.execute(new Runnable() {
592 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
593 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
594 >        try (PoolCleaner cleaner = cleaner(executor)) {
595  
596 <            public void run() {
597 <                try {
598 <                    threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
599 <                } catch (Exception e) {
600 <                    threadUnexpectedException();
601 <                }
602 <            }
717 <        });
718 <
719 <        executor.execute(new Runnable() {
720 <
721 <            public void run() {
722 <                try {
723 <                    Thread.sleep(SMALL_DELAY_MS);
724 <                    threadAssertEquals(one, q.take());
725 <                } catch (InterruptedException e) {
726 <                    threadUnexpectedException();
727 <                }
728 <            }
729 <        });
596 >            executor.execute(new CheckedRunnable() {
597 >                public void realRun() throws InterruptedException {
598 >                    threadsStarted.await();
599 >                    long startTime = System.nanoTime();
600 >                    assertTrue(q.offer(one, LONG_DELAY_MS, MILLISECONDS));
601 >                    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
602 >                }});
603  
604 <        joinPool(executor);
604 >            executor.execute(new CheckedRunnable() {
605 >                public void realRun() throws InterruptedException {
606 >                    threadsStarted.await();
607 >                    assertSame(one, q.take());
608 >                    checkEmpty(q);
609 >                }});
610 >        }
611      }
612  
613      /**
614 <     * poll retrieves elements across Executor threads
614 >     * timed poll retrieves elements across Executor threads
615       */
616      public void testPollInExecutor() {
617          final LinkedTransferQueue q = new LinkedTransferQueue();
618 <        ExecutorService executor = Executors.newFixedThreadPool(2);
619 <        executor.execute(new Runnable() {
620 <
621 <            public void run() {
622 <                threadAssertNull(q.poll());
623 <                try {
624 <                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
625 <                    threadAssertTrue(q.isEmpty());
626 <                } catch (InterruptedException e) {
627 <                    threadUnexpectedException();
628 <                }
629 <            }
630 <        });
631 <
632 <        executor.execute(new Runnable() {
633 <
634 <            public void run() {
756 <                try {
757 <                    Thread.sleep(SMALL_DELAY_MS);
618 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
619 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
620 >        try (PoolCleaner cleaner = cleaner(executor)) {
621 >
622 >            executor.execute(new CheckedRunnable() {
623 >                public void realRun() throws InterruptedException {
624 >                    assertNull(q.poll());
625 >                    threadsStarted.await();
626 >                    long startTime = System.nanoTime();
627 >                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
628 >                    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
629 >                    checkEmpty(q);
630 >                }});
631 >
632 >            executor.execute(new CheckedRunnable() {
633 >                public void realRun() throws InterruptedException {
634 >                    threadsStarted.await();
635                      q.put(one);
636 <                } catch (InterruptedException e) {
760 <                    threadUnexpectedException();
761 <                }
762 <            }
763 <        });
764 <
765 <        joinPool(executor);
766 <    }
767 <
768 <    /**
769 <     * A deserialized serialized queue has same elements in same order
770 <     */
771 <    public void testSerialization() {
772 <        LinkedTransferQueue q = populatedQueue(SIZE);
773 <
774 <        try {
775 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
776 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
777 <            out.writeObject(q);
778 <            out.close();
779 <
780 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
781 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
782 <            LinkedTransferQueue r = (LinkedTransferQueue) in.readObject();
783 <
784 <            assertEquals(q.size(), r.size());
785 <            while (!q.isEmpty()) {
786 <                assertEquals(q.remove(), r.remove());
787 <            }
788 <        } catch (Exception e) {
789 <            unexpectedException();
790 <        }
791 <    }
792 <
793 <    /**
794 <     * drainTo(null) throws NPE
795 <     */
796 <    public void testDrainToNull() {
797 <        LinkedTransferQueue q = populatedQueue(SIZE);
798 <        try {
799 <            q.drainTo(null);
800 <            shouldThrow();
801 <        } catch (NullPointerException success) {
636 >                }});
637          }
638      }
639  
640      /**
641 <     * drainTo(this) throws IAE
641 >     * A deserialized serialized queue has same elements in same order
642       */
643 <    public void testDrainToSelf() {
644 <        LinkedTransferQueue q = populatedQueue(SIZE);
645 <        try {
646 <            q.drainTo(q);
647 <            shouldThrow();
648 <        } catch (IllegalArgumentException success) {
643 >    public void testSerialization() throws Exception {
644 >        Queue x = populatedQueue(SIZE);
645 >        Queue y = serialClone(x);
646 >
647 >        assertNotSame(y, x);
648 >        assertEquals(x.size(), y.size());
649 >        assertEquals(x.toString(), y.toString());
650 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
651 >        while (!x.isEmpty()) {
652 >            assertFalse(y.isEmpty());
653 >            assertEquals(x.remove(), y.remove());
654          }
655 +        assertTrue(y.isEmpty());
656      }
657  
658      /**
# Line 821 | Line 662 | public class LinkedTransferQueueTest ext
662          LinkedTransferQueue q = populatedQueue(SIZE);
663          ArrayList l = new ArrayList();
664          q.drainTo(l);
665 <        assertEquals(q.size(), 0);
666 <        assertEquals(l.size(), SIZE);
665 >        assertEquals(0, q.size());
666 >        assertEquals(SIZE, l.size());
667          for (int i = 0; i < SIZE; ++i) {
668 <            assertEquals(l.get(i), new Integer(i));
668 >            assertEquals(i, l.get(i));
669          }
670          q.add(zero);
671          q.add(one);
# Line 833 | Line 674 | public class LinkedTransferQueueTest ext
674          assertTrue(q.contains(one));
675          l.clear();
676          q.drainTo(l);
677 <        assertEquals(q.size(), 0);
678 <        assertEquals(l.size(), 2);
677 >        assertEquals(0, q.size());
678 >        assertEquals(2, l.size());
679          for (int i = 0; i < 2; ++i) {
680 <            assertEquals(l.get(i), new Integer(i));
680 >            assertEquals(i, l.get(i));
681          }
682      }
683  
684      /**
685 <     * drainTo empties full queue, unblocking a waiting put.
685 >     * drainTo(c) empties full queue, unblocking a waiting put.
686       */
687 <    public void testDrainToWithActivePut() {
687 >    public void testDrainToWithActivePut() throws InterruptedException {
688          final LinkedTransferQueue q = populatedQueue(SIZE);
689 <        Thread t = new Thread(new Runnable() {
690 <
691 <            public void run() {
692 <                try {
693 <                    q.put(new Integer(SIZE + 1));
694 <                } catch (Exception ie) {
695 <                    threadUnexpectedException();
696 <                }
697 <            }
698 <        });
699 <        try {
859 <            t.start();
860 <            ArrayList l = new ArrayList();
861 <            q.drainTo(l);
862 <            assertTrue(l.size() >= SIZE);
863 <            for (int i = 0; i < SIZE; ++i) {
864 <                assertEquals(l.get(i), new Integer(i));
865 <            }
866 <            t.join();
867 <            assertTrue(q.size() + l.size() >= SIZE);
868 <        } catch (Exception e) {
869 <            unexpectedException();
870 <        }
871 <    }
872 <
873 <    /**
874 <     * drainTo(null, n) throws NPE
875 <     */
876 <    public void testDrainToNullN() {
877 <        LinkedTransferQueue q = populatedQueue(SIZE);
878 <        try {
879 <            q.drainTo(null, 0);
880 <            shouldThrow();
881 <        } catch (NullPointerException success) {
882 <        }
883 <    }
884 <
885 <    /**
886 <     * drainTo(this, n) throws IAE
887 <     */
888 <    public void testDrainToSelfN() {
889 <        LinkedTransferQueue q = populatedQueue(SIZE);
890 <        try {
891 <            q.drainTo(q, 0);
892 <            shouldThrow();
893 <        } catch (IllegalArgumentException success) {
894 <        }
689 >        Thread t = newStartedThread(new CheckedRunnable() {
690 >            public void realRun() {
691 >                q.put(SIZE + 1);
692 >            }});
693 >        ArrayList l = new ArrayList();
694 >        q.drainTo(l);
695 >        assertTrue(l.size() >= SIZE);
696 >        for (int i = 0; i < SIZE; ++i)
697 >            assertEquals(i, l.get(i));
698 >        awaitTermination(t);
699 >        assertTrue(q.size() + l.size() >= SIZE);
700      }
701  
702      /**
703 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
703 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
704       */
705      public void testDrainToN() {
706          LinkedTransferQueue q = new LinkedTransferQueue();
707          for (int i = 0; i < SIZE + 2; ++i) {
708              for (int j = 0; j < SIZE; j++) {
709 <                assertTrue(q.offer(new Integer(j)));
709 >                assertTrue(q.offer(j));
710              }
711              ArrayList l = new ArrayList();
712              q.drainTo(l, i);
713              int k = (i < SIZE) ? i : SIZE;
714 <            assertEquals(l.size(), k);
715 <            assertEquals(q.size(), SIZE - k);
716 <            for (int j = 0; j < k; ++j) {
717 <                assertEquals(l.get(j), new Integer(j));
718 <            }
914 <            while (q.poll() != null);
714 >            assertEquals(k, l.size());
715 >            assertEquals(SIZE - k, q.size());
716 >            for (int j = 0; j < k; ++j)
717 >                assertEquals(j, l.get(j));
718 >            do {} while (q.poll() != null);
719          }
720      }
721  
722      /**
723 <     * poll and take should decrement the waiting consumer count
723 >     * timed poll() or take() increments the waiting consumer count;
724 >     * offer(e) decrements the waiting consumer count
725       */
726 <    public void testWaitingConsumer() {
727 <        try {
728 <            final LinkedTransferQueue q = new LinkedTransferQueue();
729 <            final ConsumerObserver waiting = new ConsumerObserver();
730 <            new Thread(new Runnable() {
731 <
732 <                public void run() {
733 <                    try {
734 <                        threadAssertTrue(q.hasWaitingConsumer());
735 <                        waiting.setWaitingConsumer(q.getWaitingConsumerCount());
736 <                        threadAssertTrue(q.offer(new Object()));
737 <                    } catch (Exception ex) {
738 <                        threadUnexpectedException();
739 <                    }
726 >    public void testWaitingConsumer() throws InterruptedException {
727 >        final LinkedTransferQueue q = new LinkedTransferQueue();
728 >        assertEquals(0, q.getWaitingConsumerCount());
729 >        assertFalse(q.hasWaitingConsumer());
730 >        final CountDownLatch threadStarted = new CountDownLatch(1);
731 >
732 >        Thread t = newStartedThread(new CheckedRunnable() {
733 >            public void realRun() throws InterruptedException {
734 >                threadStarted.countDown();
735 >                long startTime = System.nanoTime();
736 >                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
737 >                assertEquals(0, q.getWaitingConsumerCount());
738 >                assertFalse(q.hasWaitingConsumer());
739 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
740 >            }});
741 >
742 >        threadStarted.await();
743 >        Callable<Boolean> oneConsumer
744 >            = new Callable<Boolean>() { public Boolean call() {
745 >                return q.hasWaitingConsumer()
746 >                && q.getWaitingConsumerCount() == 1; }};
747 >        waitForThreadToEnterWaitState(t, oneConsumer);
748 >
749 >        assertTrue(q.offer(one));
750 >        assertEquals(0, q.getWaitingConsumerCount());
751 >        assertFalse(q.hasWaitingConsumer());
752  
753 <                }
937 <            }).start();
938 <            assertTrue(q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS) != null);
939 <            assertTrue(q.getWaitingConsumerCount() < waiting.getWaitingConsumers());
940 <        } catch (Exception ex) {
941 <            this.unexpectedException();
942 <        }
753 >        awaitTermination(t);
754      }
755  
756      /**
757 <     * Inserts null into transfer throws NPE
757 >     * transfer(null) throws NullPointerException
758       */
759 <    public void testTransfer1() {
759 >    public void testTransfer1() throws InterruptedException {
760          try {
761              LinkedTransferQueue q = new LinkedTransferQueue();
762              q.transfer(null);
763              shouldThrow();
764 <        } catch (NullPointerException ex) {
954 <        } catch (Exception ex) {
955 <            this.unexpectedException();
956 <        }
764 >        } catch (NullPointerException success) {}
765      }
766  
767      /**
768 <     * transfer attempts to insert into the queue then wait until that
769 <     * object is removed via take or poll.
768 >     * transfer waits until a poll occurs. The transfered element
769 >     * is returned by the associated poll.
770       */
771 <    public void testTransfer2() {
772 <        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<Integer>();
773 <        new Thread(new Runnable() {
771 >    public void testTransfer2() throws InterruptedException {
772 >        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<>();
773 >        final CountDownLatch threadStarted = new CountDownLatch(1);
774  
775 <            public void run() {
776 <                try {
777 <                    q.transfer(new Integer(SIZE));
778 <                    threadAssertTrue(q.isEmpty());
779 <                } catch (Exception ex) {
780 <                    threadUnexpectedException();
973 <                }
974 <            }
975 <        }).start();
775 >        Thread t = newStartedThread(new CheckedRunnable() {
776 >            public void realRun() throws InterruptedException {
777 >                threadStarted.countDown();
778 >                q.transfer(five);
779 >                checkEmpty(q);
780 >            }});
781  
782 <        try {
783 <            Thread.sleep(SHORT_DELAY_MS);
784 <            assertEquals(1, q.size());
785 <            q.poll();
786 <            assertTrue(q.isEmpty());
787 <        } catch (Exception ex) {
788 <            this.unexpectedException();
789 <        }
782 >        threadStarted.await();
783 >        Callable<Boolean> oneElement
784 >            = new Callable<Boolean>() { public Boolean call() {
785 >                return !q.isEmpty() && q.size() == 1; }};
786 >        waitForThreadToEnterWaitState(t, oneElement);
787 >
788 >        assertSame(five, q.poll());
789 >        checkEmpty(q);
790 >        awaitTermination(t);
791      }
792  
793      /**
794 <     * transfer will attempt to transfer in fifo order and continue
795 <     * waiting if the element being transfered is not polled or taken
796 <     */
797 <    public void testTransfer3() {
798 <        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<Integer>();
799 <        new Thread(new Runnable() {
800 <                public void run() {
801 <                    try {
802 <                        Integer i;
803 <                        q.transfer((i = new Integer(SIZE + 1)));
804 <                        threadAssertTrue(!q.contains(i));
805 <                        threadAssertEquals(1, q.size());
806 <                    } catch (Exception ex) {
807 <                        threadUnexpectedException();
808 <                    }
809 <                }
810 <            }).start();
811 <        Thread interruptedThread =
812 <            new Thread(new Runnable() {
813 <                    public void run() {
814 <                        try {
815 <                            q.transfer(new Integer(SIZE));
816 <                            threadShouldThrow();
817 <                        } catch (InterruptedException ex) {
818 <                        }
819 <                    }
820 <                });
821 <        interruptedThread.start();
822 <        try {
1017 <            Thread.sleep(LONG_DELAY_MS);
1018 <            assertEquals(2, q.size());
1019 <            q.poll();
1020 <            Thread.sleep(LONG_DELAY_MS);
1021 <            interruptedThread.interrupt();
1022 <            assertEquals(1, q.size());
1023 <        } catch (Exception ex) {
1024 <            this.unexpectedException();
1025 <        }
794 >     * transfer waits until a poll occurs, and then transfers in fifo order
795 >     */
796 >    public void testTransfer3() throws InterruptedException {
797 >        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<>();
798 >
799 >        Thread first = newStartedThread(new CheckedRunnable() {
800 >            public void realRun() throws InterruptedException {
801 >                q.transfer(four);
802 >                assertFalse(q.contains(four));
803 >                assertEquals(1, q.size());
804 >            }});
805 >
806 >        Thread interruptedThread = newStartedThread(
807 >            new CheckedInterruptedRunnable() {
808 >                public void realRun() throws InterruptedException {
809 >                    while (q.isEmpty())
810 >                        Thread.yield();
811 >                    q.transfer(five);
812 >                }});
813 >
814 >        while (q.size() < 2)
815 >            Thread.yield();
816 >        assertEquals(2, q.size());
817 >        assertSame(four, q.poll());
818 >        first.join();
819 >        assertEquals(1, q.size());
820 >        interruptedThread.interrupt();
821 >        interruptedThread.join();
822 >        checkEmpty(q);
823      }
824  
825      /**
826 <     * transfer will wait as long as a poll or take occurs if one does occur
827 <     * the waiting is finished and the thread that tries to poll/take
1031 <     * wins in retrieving the element
826 >     * transfer waits until a poll occurs, at which point the polling
827 >     * thread returns the element
828       */
829 <    public void testTransfer4() {
829 >    public void testTransfer4() throws InterruptedException {
830          final LinkedTransferQueue q = new LinkedTransferQueue();
1035        new Thread(new Runnable() {
831  
832 <            public void run() {
833 <                try {
834 <                    q.transfer(new Integer(four));
835 <                    threadAssertFalse(q.contains(new Integer(four)));
836 <                    threadAssertEquals(new Integer(three), q.poll());
837 <                } catch (Exception ex) {
838 <                    threadUnexpectedException();
839 <                }
840 <            }
841 <        }).start();
842 <        try {
843 <            Thread.sleep(MEDIUM_DELAY_MS);
844 <            assertTrue(q.offer(three));
845 <            assertEquals(new Integer(four), q.poll());
846 <        } catch (Exception ex) {
847 <            this.unexpectedException();
848 <        }
832 >        Thread t = newStartedThread(new CheckedRunnable() {
833 >            public void realRun() throws InterruptedException {
834 >                q.transfer(four);
835 >                assertFalse(q.contains(four));
836 >                assertSame(three, q.poll());
837 >            }});
838 >
839 >        while (q.isEmpty())
840 >            Thread.yield();
841 >        assertFalse(q.isEmpty());
842 >        assertEquals(1, q.size());
843 >        assertTrue(q.offer(three));
844 >        assertSame(four, q.poll());
845 >        awaitTermination(t);
846 >    }
847 >
848 >    /**
849 >     * transfer waits until a take occurs. The transfered element
850 >     * is returned by the associated take.
851 >     */
852 >    public void testTransfer5() throws InterruptedException {
853 >        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<>();
854 >
855 >        Thread t = newStartedThread(new CheckedRunnable() {
856 >            public void realRun() throws InterruptedException {
857 >                q.transfer(four);
858 >                checkEmpty(q);
859 >            }});
860 >
861 >        while (q.isEmpty())
862 >            Thread.yield();
863 >        assertFalse(q.isEmpty());
864 >        assertEquals(1, q.size());
865 >        assertSame(four, q.take());
866 >        checkEmpty(q);
867 >        awaitTermination(t);
868      }
869  
870      /**
871 <     * Insert null into tryTransfer throws NPE
871 >     * tryTransfer(null) throws NullPointerException
872       */
873      public void testTryTransfer1() {
874 +        final LinkedTransferQueue q = new LinkedTransferQueue();
875          try {
1061            final LinkedTransferQueue q = new LinkedTransferQueue();
876              q.tryTransfer(null);
877 <            this.shouldThrow();
878 <        } catch (NullPointerException ex) {
1065 <        } catch (Exception ex) {
1066 <            this.unexpectedException();
1067 <        }
877 >            shouldThrow();
878 >        } catch (NullPointerException success) {}
879      }
880  
881      /**
882 <     * tryTransfer returns false and does not enqueue if there are no consumers
883 <     * waiting to poll or take.
882 >     * tryTransfer returns false and does not enqueue if there are no
883 >     * consumers waiting to poll or take.
884       */
885 <    public void testTryTransfer2() {
886 <        try {
887 <            final LinkedTransferQueue q = new LinkedTransferQueue();
888 <            assertFalse(q.tryTransfer(new Object()));
889 <            assertEquals(0, q.size());
1079 <        } catch (Exception ex) {
1080 <            this.unexpectedException();
1081 <        }
885 >    public void testTryTransfer2() throws InterruptedException {
886 >        final LinkedTransferQueue q = new LinkedTransferQueue();
887 >        assertFalse(q.tryTransfer(new Object()));
888 >        assertFalse(q.hasWaitingConsumer());
889 >        checkEmpty(q);
890      }
891  
892      /**
893 <     * if there is a consumer waiting poll or take tryTransfer returns
894 <     * true while enqueueing object
893 >     * If there is a consumer waiting in timed poll, tryTransfer
894 >     * returns true while successfully transfering object.
895       */
896 <    public void testTryTransfer3() {
897 <        try {
898 <            final LinkedTransferQueue q = new LinkedTransferQueue();
1091 <            new Thread(new Runnable() {
896 >    public void testTryTransfer3() throws InterruptedException {
897 >        final Object hotPotato = new Object();
898 >        final LinkedTransferQueue q = new LinkedTransferQueue();
899  
900 <                public void run() {
901 <                    try {
902 <                        threadAssertTrue(q.hasWaitingConsumer());
903 <                        threadAssertTrue(q.tryTransfer(new Object()));
904 <                    } catch (Exception ex) {
905 <                        threadUnexpectedException();
906 <                    }
900 >        Thread t = newStartedThread(new CheckedRunnable() {
901 >            public void realRun() {
902 >                while (! q.hasWaitingConsumer())
903 >                    Thread.yield();
904 >                assertTrue(q.hasWaitingConsumer());
905 >                checkEmpty(q);
906 >                assertTrue(q.tryTransfer(hotPotato));
907 >            }});
908 >
909 >        long startTime = System.nanoTime();
910 >        assertSame(hotPotato, q.poll(LONG_DELAY_MS, MILLISECONDS));
911 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
912 >        checkEmpty(q);
913 >        awaitTermination(t);
914 >    }
915  
916 <                }
917 <            }).start();
918 <            assertTrue(q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS) != null);
919 <            assertTrue(q.isEmpty());
920 <        } catch (Exception ex) {
921 <            this.unexpectedException();
922 <        }
916 >    /**
917 >     * If there is a consumer waiting in take, tryTransfer returns
918 >     * true while successfully transfering object.
919 >     */
920 >    public void testTryTransfer4() throws InterruptedException {
921 >        final Object hotPotato = new Object();
922 >        final LinkedTransferQueue q = new LinkedTransferQueue();
923 >
924 >        Thread t = newStartedThread(new CheckedRunnable() {
925 >            public void realRun() {
926 >                while (! q.hasWaitingConsumer())
927 >                    Thread.yield();
928 >                assertTrue(q.hasWaitingConsumer());
929 >                checkEmpty(q);
930 >                assertTrue(q.tryTransfer(hotPotato));
931 >            }});
932 >
933 >        assertSame(q.take(), hotPotato);
934 >        checkEmpty(q);
935 >        awaitTermination(t);
936      }
937  
938      /**
939 <     * tryTransfer waits the amount given if interrupted, show an
1112 <     * interrupted exception
939 >     * tryTransfer blocks interruptibly if no takers
940       */
941 <    public void testTryTransfer4() {
941 >    public void testTryTransfer5() throws InterruptedException {
942          final LinkedTransferQueue q = new LinkedTransferQueue();
943 <        Thread toInterrupt = new Thread(new Runnable() {
943 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
944 >        assertTrue(q.isEmpty());
945  
946 <            public void run() {
946 >        Thread t = newStartedThread(new CheckedRunnable() {
947 >            public void realRun() throws InterruptedException {
948 >                long startTime = System.nanoTime();
949 >                Thread.currentThread().interrupt();
950                  try {
951 <                    q.tryTransfer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
952 <                    threadShouldThrow();
953 <                } catch (InterruptedException ex) {
954 <                }
955 <            }
956 <        });
957 <        try {
958 <            toInterrupt.start();
959 <            Thread.sleep(SMALL_DELAY_MS);
960 <            toInterrupt.interrupt();
961 <        } catch (Exception ex) {
962 <            this.unexpectedException();
963 <        }
951 >                    q.tryTransfer(new Object(), LONG_DELAY_MS, MILLISECONDS);
952 >                    shouldThrow();
953 >                } catch (InterruptedException success) {}
954 >                assertFalse(Thread.interrupted());
955 >
956 >                pleaseInterrupt.countDown();
957 >                try {
958 >                    q.tryTransfer(new Object(), LONG_DELAY_MS, MILLISECONDS);
959 >                    shouldThrow();
960 >                } catch (InterruptedException success) {}
961 >                assertFalse(Thread.interrupted());
962 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
963 >            }});
964 >
965 >        await(pleaseInterrupt);
966 >        assertThreadStaysAlive(t);
967 >        t.interrupt();
968 >        awaitTermination(t);
969 >        checkEmpty(q);
970      }
971  
972      /**
973 <     * tryTransfer gives up after the timeout and return false
973 >     * tryTransfer gives up after the timeout and returns false
974       */
975 <    public void testTryTransfer5() {
975 >    public void testTryTransfer6() throws InterruptedException {
976          final LinkedTransferQueue q = new LinkedTransferQueue();
1140        try {
1141            new Thread(new Runnable() {
977  
978 <                public void run() {
979 <                    try {
980 <                        threadAssertFalse(q.tryTransfer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
981 <                    } catch (InterruptedException ex) {
982 <                        threadUnexpectedException();
983 <                    }
984 <                }
985 <            }).start();
986 <            Thread.sleep(LONG_DELAY_MS);
987 <            assertTrue(q.isEmpty());
988 <        } catch (Exception ex) {
1154 <            this.unexpectedException();
1155 <        }
978 >        Thread t = newStartedThread(new CheckedRunnable() {
979 >            public void realRun() throws InterruptedException {
980 >                long startTime = System.nanoTime();
981 >                assertFalse(q.tryTransfer(new Object(),
982 >                                          timeoutMillis(), MILLISECONDS));
983 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
984 >                checkEmpty(q);
985 >            }});
986 >
987 >        awaitTermination(t);
988 >        checkEmpty(q);
989      }
990  
991      /**
992       * tryTransfer waits for any elements previously in to be removed
993       * before transfering to a poll or take
994       */
995 <    public void testTryTransfer6() {
995 >    public void testTryTransfer7() throws InterruptedException {
996          final LinkedTransferQueue q = new LinkedTransferQueue();
997 <        q.offer(new Integer(four));
1165 <        new Thread(new Runnable() {
997 >        assertTrue(q.offer(four));
998  
999 <            public void run() {
1000 <                try {
1001 <                    threadAssertTrue(q.tryTransfer(new Integer(five), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
1002 <                    threadAssertTrue(q.isEmpty());
1003 <                } catch (InterruptedException ex) {
1004 <                    threadUnexpectedException();
1005 <                }
1006 <            }
1007 <        }).start();
1008 <        try {
1009 <            Thread.sleep(SHORT_DELAY_MS);
1010 <            assertEquals(2, q.size());
1011 <            assertEquals(new Integer(four), q.poll());
1012 <            assertEquals(new Integer(five), q.poll());
1013 <            assertTrue(q.isEmpty());
1182 <        } catch (Exception ex) {
1183 <            this.unexpectedException();
1184 <        }
999 >        Thread t = newStartedThread(new CheckedRunnable() {
1000 >            public void realRun() throws InterruptedException {
1001 >                long startTime = System.nanoTime();
1002 >                assertTrue(q.tryTransfer(five, LONG_DELAY_MS, MILLISECONDS));
1003 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1004 >                checkEmpty(q);
1005 >            }});
1006 >
1007 >        while (q.size() != 2)
1008 >            Thread.yield();
1009 >        assertEquals(2, q.size());
1010 >        assertSame(four, q.poll());
1011 >        assertSame(five, q.poll());
1012 >        checkEmpty(q);
1013 >        awaitTermination(t);
1014      }
1015  
1016      /**
1017 <     * tryTransfer attempts to enqueue into the q and fails returning false not
1018 <     * enqueueing and the successive poll is null
1017 >     * tryTransfer attempts to enqueue into the queue and fails
1018 >     * returning false not enqueueing and the successive poll is null
1019       */
1020 <    public void testTryTransfer7() {
1020 >    public void testTryTransfer8() throws InterruptedException {
1021          final LinkedTransferQueue q = new LinkedTransferQueue();
1022 <        q.offer(new Integer(four));
1023 <        new Thread(new Runnable() {
1024 <
1025 <            public void run() {
1026 <                try {
1027 <                    threadAssertFalse(q.tryTransfer(new Integer(five), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
1028 <                    threadAssertTrue(q.isEmpty());
1029 <                } catch (InterruptedException ex) {
1030 <                    threadUnexpectedException();
1202 <                }
1203 <            }
1204 <        }).start();
1205 <        try {
1206 <            assertEquals(1, q.size());
1207 <            assertEquals(new Integer(four), q.poll());
1208 <            Thread.sleep(MEDIUM_DELAY_MS);
1209 <            assertNull(q.poll());
1210 <        } catch (Exception ex) {
1211 <            this.unexpectedException();
1212 <        }
1022 >        assertTrue(q.offer(four));
1023 >        assertEquals(1, q.size());
1024 >        long startTime = System.nanoTime();
1025 >        assertFalse(q.tryTransfer(five, timeoutMillis(), MILLISECONDS));
1026 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
1027 >        assertEquals(1, q.size());
1028 >        assertSame(four, q.poll());
1029 >        assertNull(q.poll());
1030 >        checkEmpty(q);
1031      }
1032  
1033 <    private LinkedTransferQueue populatedQueue(
1034 <            int n) {
1035 <        LinkedTransferQueue q = new LinkedTransferQueue();
1036 <        assertTrue(q.isEmpty());
1037 <        int remainingCapacity = q.remainingCapacity();
1220 <        for (int i = 0; i <
1221 <                n; i++) {
1033 >    private LinkedTransferQueue<Integer> populatedQueue(int n) {
1034 >        LinkedTransferQueue<Integer> q = new LinkedTransferQueue<>();
1035 >        checkEmpty(q);
1036 >        for (int i = 0; i < n; i++) {
1037 >            assertEquals(i, q.size());
1038              assertTrue(q.offer(i));
1039 +            assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
1040          }
1224
1041          assertFalse(q.isEmpty());
1226        assertEquals(remainingCapacity, q.remainingCapacity());
1227        assertEquals(n, q.size());
1042          return q;
1043      }
1044  
1045 <    private static class ConsumerObserver {
1046 <
1047 <        private int waitingConsumers;
1048 <
1049 <        private ConsumerObserver() {
1050 <        }
1051 <
1052 <        private void setWaitingConsumer(int i) {
1053 <            this.waitingConsumers = i;
1054 <        }
1055 <
1056 <        private int getWaitingConsumers() {
1243 <            return waitingConsumers;
1045 >    /**
1046 >     * remove(null), contains(null) always return false
1047 >     */
1048 >    public void testNeverContainsNull() {
1049 >        Collection<?>[] qs = {
1050 >            new LinkedTransferQueue<Object>(),
1051 >            populatedQueue(2),
1052 >        };
1053 >
1054 >        for (Collection<?> q : qs) {
1055 >            assertFalse(q.contains(null));
1056 >            assertFalse(q.remove(null));
1057          }
1058      }
1059   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines