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.2 by jsr166, Fri Jul 31 23:37:31 2009 UTC vs.
Revision 1.66 by jsr166, Sun Oct 18 04:48:32 2015 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.CountDownLatch;
19 > import java.util.concurrent.Executors;
20 > import java.util.concurrent.ExecutorService;
21 > import java.util.concurrent.LinkedTransferQueue;
22 >
23   import junit.framework.Test;
22 import junit.framework.TestSuite;
24  
25 + @SuppressWarnings({"unchecked", "rawtypes"})
26   public class LinkedTransferQueueTest extends JSR166TestCase {
27 +    static class Implementation implements CollectionImplementation {
28 +        public Class<?> klazz() { return LinkedTransferQueue.class; }
29 +        public Collection emptyCollection() { return new LinkedTransferQueue(); }
30 +        public Object makeElement(int i) { return i; }
31 +        public boolean isConcurrent() { return true; }
32 +        public boolean permitsNulls() { return false; }
33 +    }
34 +
35 +    public static class Generic extends BlockingQueueTest {
36 +        protected BlockingQueue emptyCollection() {
37 +            return new LinkedTransferQueue();
38 +        }
39 +    }
40  
41      public static void main(String[] args) {
42 <        junit.textui.TestRunner.run(suite());
42 >        main(suite(), args);
43      }
44  
45      public static Test suite() {
46 <        return new TestSuite(LinkedTransferQueueTest.class);
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) {
135 >            assertTrue(q.add(i));
136          }
137      }
138  
139      /**
140 <     * 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) {
137 <        }
138 <    }
139 <
140 <    /**
141 <     * 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 <        }
162 <    }
163 <
164 <    /**
165 <     * addAll of a collection with null elements throws NPE
166 <     */
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 <        }
147 >        } catch (IllegalArgumentException success) {}
148      }
149  
150      /**
151 <     * addAll of a collection with any null elements throws NPE after
152 <     * 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<Integer>();
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) {
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 <                }
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 <     */
219 >                    shouldThrow();
220 >                } catch (InterruptedException success) {}
221 >                assertFalse(Thread.interrupted());
222  
223 <    public void testBlockingTake() {
287 <        Thread t = new Thread(new Runnable() {
288 <
289 <            public void run() {
223 >                pleaseInterrupt.countDown();
224                  try {
291                    LinkedTransferQueue q = populatedQueue(SIZE);
292                    for (int i = 0; i < SIZE; ++i) {
293                        assertEquals(i, ((Integer) q.take()).intValue());
294                    }
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();
305 <            t.join();
306 <        } catch (InterruptedException ie) {
307 <            unexpectedException();
308 <        }
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) {
329 <                assertEquals(i, ((Integer) q.poll(0, TimeUnit.MILLISECONDS)).intValue());
330 <            }
331 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
332 <        } catch (InterruptedException e) {
333 <            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 {
372 <            Thread.sleep(SHORT_DELAY_MS);
373 <            t.interrupt();
374 <            t.join();
375 <        } catch (InterruptedException ie) {
376 <            unexpectedException();
377 <        }
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 <        });
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 <        }
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 <        }
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());
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)));
480 <            assertTrue(q.take() != null);
481 <        } catch (Exception e) {
482 <            unexpectedException();
483 <        }
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);
503        int remainingCapacity = q.remainingCapacity();
403          q.clear();
404 <        assertTrue(q.isEmpty());
405 <        assertEquals(0, q.size());
507 <        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<Integer>();
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 546 | 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 555 | 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());
559 <                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++) {
572 <                assertEquals(o[i], q.take());
573 <            }
574 <        } catch (InterruptedException e) {
575 <            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());
589 <            }
590 <        } catch (InterruptedException e) {
591 <            unexpectedException();
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(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 <        }
605 <    }
606 <
607 <    /**
608 <     * 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);
613 <            Object o[] = q.toArray(new String[10]);
494 >            q.toArray(new String[10]);
495              shouldThrow();
496 <        } catch (ArrayStoreException success) {
616 <        }
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 645 | 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 654 | 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
549 >            = new LinkedTransferQueue<Integer>();
550 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
551          q.add(one);
552          q.add(two);
553          q.add(three);
554 <        assertEquals(remainingCapacity, q.remainingCapacity());
554 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
555          int k = 0;
556 <        for (Iterator it = q.iterator(); it.hasNext();) {
557 <            int i = ((Integer) (it.next())).intValue();
666 <            assertEquals(++k, i);
556 >        for (Integer n : q) {
557 >            assertEquals(++k, (int) n);
558          }
559          assertEquals(3, k);
560      }
# Line 676 | Line 567 | public class LinkedTransferQueueTest ext
567          q.add(one);
568          q.add(two);
569          q.add(three);
570 <        try {
571 <            for (Iterator it = q.iterator(); it.hasNext();) {
572 <                q.remove();
682 <                it.next();
683 <            }
684 <        } catch (ConcurrentModificationException e) {
685 <            unexpectedException();
570 >        for (Iterator it = q.iterator(); it.hasNext();) {
571 >            q.remove();
572 >            it.next();
573          }
574          assertEquals(0, q.size());
575      }
# Line 694 | Line 581 | public class LinkedTransferQueueTest ext
581          LinkedTransferQueue q = populatedQueue(SIZE);
582          String s = q.toString();
583          for (int i = 0; i < SIZE; ++i) {
584 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
584 >            assertTrue(s.contains(String.valueOf(i)));
585          }
586      }
587  
# Line 703 | Line 590 | public class LinkedTransferQueueTest ext
590       */
591      public void testOfferInExecutor() {
592          final LinkedTransferQueue q = new LinkedTransferQueue();
593 <        q.add(one);
594 <        q.add(two);
595 <        ExecutorService executor = Executors.newFixedThreadPool(2);
709 <        executor.execute(new Runnable() {
593 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
594 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
595 >        try (PoolCleaner cleaner = cleaner(executor)) {
596  
597 <            public void run() {
598 <                try {
599 <                    threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
600 <                } catch (Exception e) {
601 <                    threadUnexpectedException();
602 <                }
603 <            }
718 <        });
597 >            executor.execute(new CheckedRunnable() {
598 >                public void realRun() throws InterruptedException {
599 >                    threadsStarted.await();
600 >                    long startTime = System.nanoTime();
601 >                    assertTrue(q.offer(one, LONG_DELAY_MS, MILLISECONDS));
602 >                    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
603 >                }});
604  
605 <        executor.execute(new Runnable() {
606 <
607 <            public void run() {
608 <                try {
609 <                    Thread.sleep(SMALL_DELAY_MS);
610 <                    threadAssertEquals(one, q.take());
611 <                } catch (InterruptedException e) {
727 <                    threadUnexpectedException();
728 <                }
729 <            }
730 <        });
731 <
732 <        joinPool(executor);
605 >            executor.execute(new CheckedRunnable() {
606 >                public void realRun() throws InterruptedException {
607 >                    threadsStarted.await();
608 >                    assertSame(one, q.take());
609 >                    checkEmpty(q);
610 >                }});
611 >        }
612      }
613  
614      /**
615 <     * poll retrieves elements across Executor threads
615 >     * timed poll retrieves elements across Executor threads
616       */
617      public void testPollInExecutor() {
618          final LinkedTransferQueue q = new LinkedTransferQueue();
619 <        ExecutorService executor = Executors.newFixedThreadPool(2);
620 <        executor.execute(new Runnable() {
621 <
622 <            public void run() {
623 <                threadAssertNull(q.poll());
624 <                try {
625 <                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
626 <                    threadAssertTrue(q.isEmpty());
627 <                } catch (InterruptedException e) {
628 <                    threadUnexpectedException();
629 <                }
630 <            }
631 <        });
632 <
633 <        executor.execute(new Runnable() {
634 <
635 <            public void run() {
757 <                try {
758 <                    Thread.sleep(SMALL_DELAY_MS);
619 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
620 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
621 >        try (PoolCleaner cleaner = cleaner(executor)) {
622 >
623 >            executor.execute(new CheckedRunnable() {
624 >                public void realRun() throws InterruptedException {
625 >                    assertNull(q.poll());
626 >                    threadsStarted.await();
627 >                    long startTime = System.nanoTime();
628 >                    assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
629 >                    assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
630 >                    checkEmpty(q);
631 >                }});
632 >
633 >            executor.execute(new CheckedRunnable() {
634 >                public void realRun() throws InterruptedException {
635 >                    threadsStarted.await();
636                      q.put(one);
637 <                } 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();
637 >                }});
638          }
639      }
640  
641      /**
642 <     * drainTo(null) throws NPE
642 >     * A deserialized serialized queue has same elements in same order
643       */
644 <    public void testDrainToNull() {
645 <        LinkedTransferQueue q = populatedQueue(SIZE);
646 <        try {
647 <            q.drainTo(null);
648 <            shouldThrow();
649 <        } catch (NullPointerException success) {
650 <        }
651 <    }
652 <
653 <    /**
654 <     * drainTo(this) throws IAE
808 <     */
809 <    public void testDrainToSelf() {
810 <        LinkedTransferQueue q = populatedQueue(SIZE);
811 <        try {
812 <            q.drainTo(q);
813 <            shouldThrow();
814 <        } catch (IllegalArgumentException success) {
644 >    public void testSerialization() throws Exception {
645 >        Queue x = populatedQueue(SIZE);
646 >        Queue y = serialClone(x);
647 >
648 >        assertNotSame(y, x);
649 >        assertEquals(x.size(), y.size());
650 >        assertEquals(x.toString(), y.toString());
651 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
652 >        while (!x.isEmpty()) {
653 >            assertFalse(y.isEmpty());
654 >            assertEquals(x.remove(), y.remove());
655          }
656 +        assertTrue(y.isEmpty());
657      }
658  
659      /**
# Line 822 | Line 663 | public class LinkedTransferQueueTest ext
663          LinkedTransferQueue q = populatedQueue(SIZE);
664          ArrayList l = new ArrayList();
665          q.drainTo(l);
666 <        assertEquals(q.size(), 0);
667 <        assertEquals(l.size(), SIZE);
666 >        assertEquals(0, q.size());
667 >        assertEquals(SIZE, l.size());
668          for (int i = 0; i < SIZE; ++i) {
669 <            assertEquals(l.get(i), new Integer(i));
669 >            assertEquals(i, l.get(i));
670          }
671          q.add(zero);
672          q.add(one);
# Line 834 | Line 675 | public class LinkedTransferQueueTest ext
675          assertTrue(q.contains(one));
676          l.clear();
677          q.drainTo(l);
678 <        assertEquals(q.size(), 0);
679 <        assertEquals(l.size(), 2);
678 >        assertEquals(0, q.size());
679 >        assertEquals(2, l.size());
680          for (int i = 0; i < 2; ++i) {
681 <            assertEquals(l.get(i), new Integer(i));
681 >            assertEquals(i, l.get(i));
682          }
683      }
684  
685      /**
686 <     * drainTo empties full queue, unblocking a waiting put.
686 >     * drainTo(c) empties full queue, unblocking a waiting put.
687       */
688 <    public void testDrainToWithActivePut() {
688 >    public void testDrainToWithActivePut() throws InterruptedException {
689          final LinkedTransferQueue q = populatedQueue(SIZE);
690 <        Thread t = new Thread(new Runnable() {
691 <
692 <            public void run() {
693 <                try {
694 <                    q.put(new Integer(SIZE + 1));
695 <                } catch (Exception ie) {
696 <                    threadUnexpectedException();
697 <                }
698 <            }
699 <        });
700 <        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 <        }
690 >        Thread t = newStartedThread(new CheckedRunnable() {
691 >            public void realRun() {
692 >                q.put(SIZE + 1);
693 >            }});
694 >        ArrayList l = new ArrayList();
695 >        q.drainTo(l);
696 >        assertTrue(l.size() >= SIZE);
697 >        for (int i = 0; i < SIZE; ++i)
698 >            assertEquals(i, l.get(i));
699 >        awaitTermination(t);
700 >        assertTrue(q.size() + l.size() >= SIZE);
701      }
702  
703      /**
704 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
704 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
705       */
706      public void testDrainToN() {
707          LinkedTransferQueue q = new LinkedTransferQueue();
708          for (int i = 0; i < SIZE + 2; ++i) {
709              for (int j = 0; j < SIZE; j++) {
710 <                assertTrue(q.offer(new Integer(j)));
710 >                assertTrue(q.offer(j));
711              }
712              ArrayList l = new ArrayList();
713              q.drainTo(l, i);
714              int k = (i < SIZE) ? i : SIZE;
715 <            assertEquals(l.size(), k);
716 <            assertEquals(q.size(), SIZE - k);
717 <            for (int j = 0; j < k; ++j) {
718 <                assertEquals(l.get(j), new Integer(j));
719 <            }
915 <            while (q.poll() != null);
715 >            assertEquals(k, l.size());
716 >            assertEquals(SIZE - k, q.size());
717 >            for (int j = 0; j < k; ++j)
718 >                assertEquals(j, l.get(j));
719 >            do {} while (q.poll() != null);
720          }
721      }
722  
723 <    /*
724 <     * poll and take should decrement the waiting consumer count
723 >    /**
724 >     * timed poll() or take() increments the waiting consumer count;
725 >     * offer(e) decrements the waiting consumer count
726       */
727 <    public void testWaitingConsumer() {
728 <        try {
729 <            final LinkedTransferQueue q = new LinkedTransferQueue();
730 <            final ConsumerObserver waiting = new ConsumerObserver();
731 <            new Thread(new Runnable() {
927 <
928 <                public void run() {
929 <                    try {
930 <                        threadAssertTrue(q.hasWaitingConsumer());
931 <                        waiting.setWaitingConsumer(q.getWaitingConsumerCount());
932 <                        threadAssertTrue(q.offer(new Object()));
933 <                    } catch (Exception ex) {
934 <                        threadUnexpectedException();
935 <                    }
727 >    public void testWaitingConsumer() throws InterruptedException {
728 >        final LinkedTransferQueue q = new LinkedTransferQueue();
729 >        assertEquals(0, q.getWaitingConsumerCount());
730 >        assertFalse(q.hasWaitingConsumer());
731 >        final CountDownLatch threadStarted = new CountDownLatch(1);
732  
733 <                }
734 <            }).start();
735 <            assertTrue(q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS) != null);
736 <            assertTrue(q.getWaitingConsumerCount() < waiting.getWaitingConsumers());
737 <        } catch (Exception ex) {
738 <            this.unexpectedException();
739 <        }
733 >        Thread t = newStartedThread(new CheckedRunnable() {
734 >            public void realRun() throws InterruptedException {
735 >                threadStarted.countDown();
736 >                long startTime = System.nanoTime();
737 >                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
738 >                assertEquals(0, q.getWaitingConsumerCount());
739 >                assertFalse(q.hasWaitingConsumer());
740 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
741 >            }});
742 >
743 >        threadStarted.await();
744 >        waitForThreadToEnterWaitState(t);
745 >        assertEquals(1, q.getWaitingConsumerCount());
746 >        assertTrue(q.hasWaitingConsumer());
747 >
748 >        assertTrue(q.offer(one));
749 >        assertEquals(0, q.getWaitingConsumerCount());
750 >        assertFalse(q.hasWaitingConsumer());
751 >
752 >        awaitTermination(t);
753      }
945    /*
946     * Inserts null into transfer throws NPE
947     */
754  
755 <    public void testTransfer1() {
755 >    /**
756 >     * transfer(null) throws NullPointerException
757 >     */
758 >    public void testTransfer1() throws InterruptedException {
759          try {
760              LinkedTransferQueue q = new LinkedTransferQueue();
761              q.transfer(null);
762              shouldThrow();
763 <        } catch (NullPointerException ex) {
955 <        } catch (Exception ex) {
956 <            this.unexpectedException();
957 <        }
763 >        } catch (NullPointerException success) {}
764      }
765  
766 <    /*
767 <     * transfer attempts to insert into the queue then wait until that
768 <     * object is removed via take or poll.
766 >    /**
767 >     * transfer waits until a poll occurs. The transfered element
768 >     * is returned by this associated poll.
769       */
770 <    public void testTransfer2() {
771 <        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<Integer>();
772 <        new Thread(new Runnable() {
770 >    public void testTransfer2() throws InterruptedException {
771 >        final LinkedTransferQueue<Integer> q
772 >            = new LinkedTransferQueue<Integer>();
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();
974 <                }
975 <            }
976 <        }).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 <        }
790 <    }
791 <    /*
792 <     * transfer will attempt to transfer in fifo order and continue waiting if
793 <     * the element being transfered is not polled or taken
794 <     */
795 <
796 <    public void testTransfer3() {
797 <        final LinkedTransferQueue<Integer> q = new LinkedTransferQueue<Integer>();
798 <        new Thread(new Runnable() {
799 <                public void run() {
800 <                    try {
801 <                        Integer i;
802 <                        q.transfer((i = new Integer(SIZE + 1)));
803 <                        threadAssertTrue(!q.contains(i));
804 <                        threadAssertEquals(1, q.size());
805 <                    } catch (Exception ex) {
806 <                        threadUnexpectedException();
807 <                    }
808 <                }
809 <            }).start();
810 <        Thread interruptedThread =
811 <            new Thread(new Runnable() {
812 <                    public void run() {
813 <                        try {
814 <                            q.transfer(new Integer(SIZE));
815 <                            threadShouldThrow();
816 <                        } catch (InterruptedException ex) {
817 <                        }
818 <                    }
819 <                });
820 <        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 <        }
782 >        threadStarted.await();
783 >        waitForThreadToEnterWaitState(t);
784 >        assertEquals(1, q.size());
785 >        assertSame(five, q.poll());
786 >        checkEmpty(q);
787 >        awaitTermination(t);
788 >    }
789 >
790 >    /**
791 >     * transfer waits until a poll occurs, and then transfers in fifo order
792 >     */
793 >    public void testTransfer3() throws InterruptedException {
794 >        final LinkedTransferQueue<Integer> q
795 >            = new LinkedTransferQueue<Integer>();
796 >
797 >        Thread first = newStartedThread(new CheckedRunnable() {
798 >            public void realRun() throws InterruptedException {
799 >                q.transfer(four);
800 >                assertTrue(!q.contains(four));
801 >                assertEquals(1, q.size());
802 >            }});
803 >
804 >        Thread interruptedThread = newStartedThread(
805 >            new CheckedInterruptedRunnable() {
806 >                public void realRun() throws InterruptedException {
807 >                    while (q.isEmpty())
808 >                        Thread.yield();
809 >                    q.transfer(five);
810 >                }});
811 >
812 >        while (q.size() < 2)
813 >            Thread.yield();
814 >        assertEquals(2, q.size());
815 >        assertSame(four, q.poll());
816 >        first.join();
817 >        assertEquals(1, q.size());
818 >        interruptedThread.interrupt();
819 >        interruptedThread.join();
820 >        checkEmpty(q);
821      }
822  
823      /**
824 <     * transfer will wait as long as a poll or take occurs if one does occur
825 <     * the waiting is finished and the thread that tries to poll/take
1032 <     * wins in retrieving the element
824 >     * transfer waits until a poll occurs, at which point the polling
825 >     * thread returns the element
826       */
827 <    public void testTransfer4() {
827 >    public void testTransfer4() throws InterruptedException {
828          final LinkedTransferQueue q = new LinkedTransferQueue();
1036        new Thread(new Runnable() {
829  
830 <            public void run() {
831 <                try {
832 <                    q.transfer(new Integer(four));
833 <                    threadAssertFalse(q.contains(new Integer(four)));
834 <                    threadAssertEquals(new Integer(three), q.poll());
835 <                } catch (Exception ex) {
836 <                    threadUnexpectedException();
837 <                }
838 <            }
839 <        }).start();
840 <        try {
841 <            Thread.sleep(MEDIUM_DELAY_MS);
842 <            assertTrue(q.offer(three));
843 <            assertEquals(new Integer(four), q.poll());
1052 <        } catch (Exception ex) {
1053 <            this.unexpectedException();
1054 <        }
830 >        Thread t = newStartedThread(new CheckedRunnable() {
831 >            public void realRun() throws InterruptedException {
832 >                q.transfer(four);
833 >                assertFalse(q.contains(four));
834 >                assertSame(three, q.poll());
835 >            }});
836 >
837 >        while (q.isEmpty())
838 >            Thread.yield();
839 >        assertFalse(q.isEmpty());
840 >        assertEquals(1, q.size());
841 >        assertTrue(q.offer(three));
842 >        assertSame(four, q.poll());
843 >        awaitTermination(t);
844      }
845 <    /*
846 <     * Insert null into trTransfer throws NPE
845 >
846 >    /**
847 >     * transfer waits until a take occurs. The transfered element
848 >     * is returned by this associated take.
849       */
850 +    public void testTransfer5() throws InterruptedException {
851 +        final LinkedTransferQueue<Integer> q
852 +            = new LinkedTransferQueue<Integer>();
853  
854 +        Thread t = newStartedThread(new CheckedRunnable() {
855 +            public void realRun() throws InterruptedException {
856 +                q.transfer(four);
857 +                checkEmpty(q);
858 +            }});
859 +
860 +        while (q.isEmpty())
861 +            Thread.yield();
862 +        assertFalse(q.isEmpty());
863 +        assertEquals(1, q.size());
864 +        assertSame(four, q.take());
865 +        checkEmpty(q);
866 +        awaitTermination(t);
867 +    }
868 +
869 +    /**
870 +     * tryTransfer(null) throws NullPointerException
871 +     */
872      public void testTryTransfer1() {
873 +        final LinkedTransferQueue q = new LinkedTransferQueue();
874          try {
1062            final LinkedTransferQueue q = new LinkedTransferQueue();
875              q.tryTransfer(null);
876 <            this.shouldThrow();
877 <        } catch (NullPointerException ex) {
1066 <        } catch (Exception ex) {
1067 <            this.unexpectedException();
1068 <        }
876 >            shouldThrow();
877 >        } catch (NullPointerException success) {}
878      }
1070    /*
1071     * tryTransfer returns false and does not enqueue if there are no consumers
1072     * waiting to poll or take.
1073     */
879  
880 <    public void testTryTransfer2() {
881 <        try {
882 <            final LinkedTransferQueue q = new LinkedTransferQueue();
883 <            assertFalse(q.tryTransfer(new Object()));
884 <            assertEquals(0, q.size());
885 <        } catch (Exception ex) {
886 <            this.unexpectedException();
887 <        }
880 >    /**
881 >     * tryTransfer returns false and does not enqueue if there are no
882 >     * consumers waiting to poll or take.
883 >     */
884 >    public void testTryTransfer2() throws InterruptedException {
885 >        final LinkedTransferQueue q = new LinkedTransferQueue();
886 >        assertFalse(q.tryTransfer(new Object()));
887 >        assertFalse(q.hasWaitingConsumer());
888 >        checkEmpty(q);
889      }
890 <    /*
891 <     * if there is a consumer waiting poll or take tryTransfer returns
892 <     * true while enqueueing object
890 >
891 >    /**
892 >     * If there is a consumer waiting in timed poll, tryTransfer
893 >     * returns true while successfully transfering object.
894       */
895 +    public void testTryTransfer3() throws InterruptedException {
896 +        final Object hotPotato = new Object();
897 +        final LinkedTransferQueue q = new LinkedTransferQueue();
898  
899 <    public void testTryTransfer3() {
900 <        try {
901 <            final LinkedTransferQueue q = new LinkedTransferQueue();
902 <            new Thread(new Runnable() {
899 >        Thread t = newStartedThread(new CheckedRunnable() {
900 >            public void realRun() {
901 >                while (! q.hasWaitingConsumer())
902 >                    Thread.yield();
903 >                assertTrue(q.hasWaitingConsumer());
904 >                checkEmpty(q);
905 >                assertTrue(q.tryTransfer(hotPotato));
906 >            }});
907 >
908 >        long startTime = System.nanoTime();
909 >        assertSame(hotPotato, q.poll(LONG_DELAY_MS, MILLISECONDS));
910 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
911 >        checkEmpty(q);
912 >        awaitTermination(t);
913 >    }
914 >
915 >    /**
916 >     * If there is a consumer waiting in take, tryTransfer returns
917 >     * true while successfully transfering object.
918 >     */
919 >    public void testTryTransfer4() throws InterruptedException {
920 >        final Object hotPotato = new Object();
921 >        final LinkedTransferQueue q = new LinkedTransferQueue();
922  
923 <                public void run() {
924 <                    try {
925 <                        threadAssertTrue(q.hasWaitingConsumer());
926 <                        threadAssertTrue(q.tryTransfer(new Object()));
927 <                    } catch (Exception ex) {
928 <                        threadUnexpectedException();
929 <                    }
923 >        Thread t = newStartedThread(new CheckedRunnable() {
924 >            public void realRun() {
925 >                while (! q.hasWaitingConsumer())
926 >                    Thread.yield();
927 >                assertTrue(q.hasWaitingConsumer());
928 >                checkEmpty(q);
929 >                assertTrue(q.tryTransfer(hotPotato));
930 >            }});
931  
932 <                }
933 <            }).start();
934 <            assertTrue(q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS) != null);
1105 <            assertTrue(q.isEmpty());
1106 <        } catch (Exception ex) {
1107 <            this.unexpectedException();
1108 <        }
932 >        assertSame(q.take(), hotPotato);
933 >        checkEmpty(q);
934 >        awaitTermination(t);
935      }
936  
937 <    /*
938 <     * tryTransfer waits the amount given if interrupted, show an
1113 <     * interrupted exception
937 >    /**
938 >     * tryTransfer blocks interruptibly if no takers
939       */
940 <    public void testTryTransfer4() {
940 >    public void testTryTransfer5() throws InterruptedException {
941          final LinkedTransferQueue q = new LinkedTransferQueue();
942 <        Thread toInterrupt = new Thread(new Runnable() {
942 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
943 >        assertTrue(q.isEmpty());
944  
945 <            public void run() {
945 >        Thread t = newStartedThread(new CheckedRunnable() {
946 >            public void realRun() throws InterruptedException {
947 >                long startTime = System.nanoTime();
948 >                Thread.currentThread().interrupt();
949                  try {
950 <                    q.tryTransfer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
951 <                    threadShouldThrow();
952 <                } catch (InterruptedException ex) {
953 <                }
954 <            }
955 <        });
956 <        try {
957 <            toInterrupt.start();
958 <            Thread.sleep(SMALL_DELAY_MS);
959 <            toInterrupt.interrupt();
960 <        } catch (Exception ex) {
961 <            this.unexpectedException();
962 <        }
950 >                    q.tryTransfer(new Object(), LONG_DELAY_MS, MILLISECONDS);
951 >                    shouldThrow();
952 >                } catch (InterruptedException success) {}
953 >                assertFalse(Thread.interrupted());
954 >
955 >                pleaseInterrupt.countDown();
956 >                try {
957 >                    q.tryTransfer(new Object(), LONG_DELAY_MS, MILLISECONDS);
958 >                    shouldThrow();
959 >                } catch (InterruptedException success) {}
960 >                assertFalse(Thread.interrupted());
961 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
962 >            }});
963 >
964 >        await(pleaseInterrupt);
965 >        assertThreadStaysAlive(t);
966 >        t.interrupt();
967 >        awaitTermination(t);
968 >        checkEmpty(q);
969      }
970  
971 <    /*
972 <     * tryTransfer gives up after the timeout and return false
971 >    /**
972 >     * tryTransfer gives up after the timeout and returns false
973       */
974 <    public void testTryTransfer5() {
974 >    public void testTryTransfer6() throws InterruptedException {
975          final LinkedTransferQueue q = new LinkedTransferQueue();
1141        try {
1142            new Thread(new Runnable() {
976  
977 <                public void run() {
978 <                    try {
979 <                        threadAssertFalse(q.tryTransfer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
980 <                    } catch (InterruptedException ex) {
981 <                        threadUnexpectedException();
982 <                    }
983 <                }
984 <            }).start();
985 <            Thread.sleep(LONG_DELAY_MS);
986 <            assertTrue(q.isEmpty());
987 <        } catch (Exception ex) {
1155 <            this.unexpectedException();
1156 <        }
977 >        Thread t = newStartedThread(new CheckedRunnable() {
978 >            public void realRun() throws InterruptedException {
979 >                long startTime = System.nanoTime();
980 >                assertFalse(q.tryTransfer(new Object(),
981 >                                          timeoutMillis(), MILLISECONDS));
982 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
983 >                checkEmpty(q);
984 >            }});
985 >
986 >        awaitTermination(t);
987 >        checkEmpty(q);
988      }
989  
990 <    /*
990 >    /**
991       * tryTransfer waits for any elements previously in to be removed
992       * before transfering to a poll or take
993       */
994 <    public void testTryTransfer6() {
994 >    public void testTryTransfer7() throws InterruptedException {
995          final LinkedTransferQueue q = new LinkedTransferQueue();
996 <        q.offer(new Integer(four));
1166 <        new Thread(new Runnable() {
996 >        assertTrue(q.offer(four));
997  
998 <            public void run() {
999 <                try {
1000 <                    threadAssertTrue(q.tryTransfer(new Integer(five), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
1001 <                    threadAssertTrue(q.isEmpty());
1002 <                } catch (InterruptedException ex) {
1003 <                    threadUnexpectedException();
1004 <                }
1005 <            }
1006 <        }).start();
1007 <        try {
1008 <            Thread.sleep(SHORT_DELAY_MS);
1009 <            assertEquals(2, q.size());
1010 <            assertEquals(new Integer(four), q.poll());
1011 <            assertEquals(new Integer(five), q.poll());
1012 <            assertTrue(q.isEmpty());
1183 <        } catch (Exception ex) {
1184 <            this.unexpectedException();
1185 <        }
998 >        Thread t = newStartedThread(new CheckedRunnable() {
999 >            public void realRun() throws InterruptedException {
1000 >                long startTime = System.nanoTime();
1001 >                assertTrue(q.tryTransfer(five, LONG_DELAY_MS, MILLISECONDS));
1002 >                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1003 >                checkEmpty(q);
1004 >            }});
1005 >
1006 >        while (q.size() != 2)
1007 >            Thread.yield();
1008 >        assertEquals(2, q.size());
1009 >        assertSame(four, q.poll());
1010 >        assertSame(five, q.poll());
1011 >        checkEmpty(q);
1012 >        awaitTermination(t);
1013      }
1014  
1015 <    /*
1016 <     * tryTransfer attempts to enqueue into the q and fails returning false not
1017 <     * enqueueing and the successing poll is null
1015 >    /**
1016 >     * tryTransfer attempts to enqueue into the queue and fails
1017 >     * returning false not enqueueing and the successive poll is null
1018       */
1019 <    public void testTryTransfer7() {
1019 >    public void testTryTransfer8() throws InterruptedException {
1020          final LinkedTransferQueue q = new LinkedTransferQueue();
1021 <        q.offer(new Integer(four));
1022 <        new Thread(new Runnable() {
1023 <
1024 <            public void run() {
1025 <                try {
1026 <                    threadAssertFalse(q.tryTransfer(new Integer(five), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
1027 <                    threadAssertTrue(q.isEmpty());
1028 <                } catch (InterruptedException ex) {
1029 <                    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 <        }
1021 >        assertTrue(q.offer(four));
1022 >        assertEquals(1, q.size());
1023 >        long startTime = System.nanoTime();
1024 >        assertFalse(q.tryTransfer(five, timeoutMillis(), MILLISECONDS));
1025 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
1026 >        assertEquals(1, q.size());
1027 >        assertSame(four, q.poll());
1028 >        assertNull(q.poll());
1029 >        checkEmpty(q);
1030      }
1031  
1032 <    private LinkedTransferQueue populatedQueue(
1033 <            int n) {
1034 <        LinkedTransferQueue q = new LinkedTransferQueue();
1035 <        assertTrue(q.isEmpty());
1036 <        int remainingCapacity = q.remainingCapacity();
1221 <        for (int i = 0; i <
1222 <                n; i++) {
1032 >    private LinkedTransferQueue<Integer> populatedQueue(int n) {
1033 >        LinkedTransferQueue<Integer> q = new LinkedTransferQueue<Integer>();
1034 >        checkEmpty(q);
1035 >        for (int i = 0; i < n; i++) {
1036 >            assertEquals(i, q.size());
1037              assertTrue(q.offer(i));
1038 +            assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
1039          }
1225
1040          assertFalse(q.isEmpty());
1227        assertEquals(remainingCapacity, q.remainingCapacity());
1228        assertEquals(n, q.size());
1041          return q;
1042      }
1043  
1044 <    private static class ConsumerObserver {
1045 <
1046 <        private int waitingConsumers;
1047 <
1048 <        private ConsumerObserver() {
1049 <        }
1050 <
1051 <        private void setWaitingConsumer(int i) {
1052 <            this.waitingConsumers = i;
1053 <        }
1054 <
1055 <        private int getWaitingConsumers() {
1244 <            return waitingConsumers;
1044 >    /**
1045 >     * remove(null), contains(null) always return false
1046 >     */
1047 >    public void testNeverContainsNull() {
1048 >        Collection<?>[] qs = {
1049 >            new LinkedTransferQueue<Object>(),
1050 >            populatedQueue(2),
1051 >        };
1052 >
1053 >        for (Collection<?> q : qs) {
1054 >            assertFalse(q.contains(null));
1055 >            assertFalse(q.remove(null));
1056          }
1057      }
1058   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines