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.1 by dl, Fri Jul 31 23:02:49 2009 UTC vs.
Revision 1.84 by jsr166, Fri Sep 6 22:43:50 2019 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines