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

Comparing jsr166/src/test/tck/LinkedBlockingQueueTest.java (file contents):
Revision 1.15 by jsr166, Sat Nov 21 02:07:26 2009 UTC vs.
Revision 1.46 by jsr166, Tue May 31 16:16:24 2011 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9   import junit.framework.*;
10 < import java.util.*;
11 < import java.util.concurrent.*;
12 < import java.io.*;
10 > import java.util.Arrays;
11 > import java.util.ArrayList;
12 > import java.util.Collection;
13 > import java.util.Iterator;
14 > import java.util.NoSuchElementException;
15 > import java.util.Queue;
16 > import java.util.concurrent.BlockingQueue;
17 > import java.util.concurrent.CountDownLatch;
18 > import java.util.concurrent.LinkedBlockingQueue;
19 > import java.util.concurrent.Executors;
20 > import java.util.concurrent.ExecutorService;
21 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
22  
23   public class LinkedBlockingQueueTest extends JSR166TestCase {
24  
25 +    public static class Unbounded extends BlockingQueueTest {
26 +        protected BlockingQueue emptyCollection() {
27 +            return new LinkedBlockingQueue();
28 +        }
29 +    }
30 +
31 +    public static class Bounded extends BlockingQueueTest {
32 +        protected BlockingQueue emptyCollection() {
33 +            return new LinkedBlockingQueue(20);
34 +        }
35 +    }
36 +
37      public static void main(String[] args) {
38 <        junit.textui.TestRunner.run (suite());
38 >        junit.textui.TestRunner.run(suite());
39      }
40  
41      public static Test suite() {
42 <        return new TestSuite(LinkedBlockingQueueTest.class);
42 >        return newTestSuite(LinkedBlockingQueueTest.class,
43 >                            new Unbounded().testSuite(),
44 >                            new Bounded().testSuite());
45      }
46  
24
47      /**
48       * Create a queue of given size containing consecutive
49       * Integers 0 ... n.
50       */
51 <    private LinkedBlockingQueue populatedQueue(int n) {
52 <        LinkedBlockingQueue q = new LinkedBlockingQueue(n);
51 >    private LinkedBlockingQueue<Integer> populatedQueue(int n) {
52 >        LinkedBlockingQueue<Integer> q =
53 >            new LinkedBlockingQueue<Integer>(n);
54          assertTrue(q.isEmpty());
55          for (int i = 0; i < n; i++)
56              assertTrue(q.offer(new Integer(i)));
# Line 47 | Line 70 | public class LinkedBlockingQueueTest ext
70      }
71  
72      /**
73 <     * Constructor throws IAE if  capacity argument nonpositive
73 >     * Constructor throws IllegalArgumentException if capacity argument nonpositive
74       */
75      public void testConstructor2() {
76          try {
77 <            LinkedBlockingQueue q = new LinkedBlockingQueue(0);
77 >            new LinkedBlockingQueue(0);
78              shouldThrow();
79 <        }
57 <        catch (IllegalArgumentException success) {}
79 >        } catch (IllegalArgumentException success) {}
80      }
81  
82      /**
83 <     * Initializing from null Collection throws NPE
83 >     * Initializing from null Collection throws NullPointerException
84       */
85      public void testConstructor3() {
86          try {
87 <            LinkedBlockingQueue q = new LinkedBlockingQueue(null);
87 >            new LinkedBlockingQueue(null);
88              shouldThrow();
89 <        }
68 <        catch (NullPointerException success) {}
89 >        } catch (NullPointerException success) {}
90      }
91  
92      /**
93 <     * Initializing from Collection of null elements throws NPE
93 >     * Initializing from Collection of null elements throws NullPointerException
94       */
95      public void testConstructor4() {
96 +        Collection<Integer> elements = Arrays.asList(new Integer[SIZE]);
97          try {
98 <            Integer[] ints = new Integer[SIZE];
77 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
98 >            new LinkedBlockingQueue(elements);
99              shouldThrow();
100 <        }
80 <        catch (NullPointerException success) {}
100 >        } catch (NullPointerException success) {}
101      }
102  
103      /**
104 <     * Initializing from Collection with some null elements throws NPE
104 >     * Initializing from Collection with some null elements throws
105 >     * NullPointerException
106       */
107      public void testConstructor5() {
108 +        Integer[] ints = new Integer[SIZE];
109 +        for (int i = 0; i < SIZE-1; ++i)
110 +            ints[i] = new Integer(i);
111 +        Collection<Integer> elements = Arrays.asList(ints);
112          try {
113 <            Integer[] ints = new Integer[SIZE];
89 <            for (int i = 0; i < SIZE-1; ++i)
90 <                ints[i] = new Integer(i);
91 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
113 >            new LinkedBlockingQueue(elements);
114              shouldThrow();
115 <        }
94 <        catch (NullPointerException success) {}
115 >        } catch (NullPointerException success) {}
116      }
117  
118      /**
119       * Queue contains all elements of collection used to initialize
120       */
121      public void testConstructor6() {
122 <        try {
123 <            Integer[] ints = new Integer[SIZE];
124 <            for (int i = 0; i < SIZE; ++i)
125 <                ints[i] = new Integer(i);
126 <            LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
127 <            for (int i = 0; i < SIZE; ++i)
107 <                assertEquals(ints[i], q.poll());
108 <        }
109 <        finally {}
122 >        Integer[] ints = new Integer[SIZE];
123 >        for (int i = 0; i < SIZE; ++i)
124 >            ints[i] = new Integer(i);
125 >        LinkedBlockingQueue q = new LinkedBlockingQueue(Arrays.asList(ints));
126 >        for (int i = 0; i < SIZE; ++i)
127 >            assertEquals(ints[i], q.poll());
128      }
129  
130      /**
# Line 142 | Line 160 | public class LinkedBlockingQueueTest ext
160      }
161  
162      /**
145     * offer(null) throws NPE
146     */
147    public void testOfferNull() {
148        try {
149            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
150            q.offer(null);
151            shouldThrow();
152        } catch (NullPointerException success) { }
153    }
154
155    /**
156     * add(null) throws NPE
157     */
158    public void testAddNull() {
159        try {
160            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
161            q.add(null);
162            shouldThrow();
163        } catch (NullPointerException success) { }
164    }
165
166    /**
163       * Offer succeeds if not full; fails if full
164       */
165      public void testOffer() {
# Line 173 | Line 169 | public class LinkedBlockingQueueTest ext
169      }
170  
171      /**
172 <     * add succeeds if not full; throws ISE if full
172 >     * add succeeds if not full; throws IllegalStateException if full
173       */
174      public void testAdd() {
175 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
176 +        for (int i = 0; i < SIZE; ++i)
177 +            assertTrue(q.add(new Integer(i)));
178 +        assertEquals(0, q.remainingCapacity());
179          try {
180            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
181            for (int i = 0; i < SIZE; ++i) {
182                assertTrue(q.add(new Integer(i)));
183            }
184            assertEquals(0, q.remainingCapacity());
180              q.add(new Integer(SIZE));
186        } catch (IllegalStateException success) {
187        }
188    }
189
190    /**
191     * addAll(null) throws NPE
192     */
193    public void testAddAll1() {
194        try {
195            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
196            q.addAll(null);
181              shouldThrow();
182 <        }
199 <        catch (NullPointerException success) {}
182 >        } catch (IllegalStateException success) {}
183      }
184  
185      /**
186 <     * addAll(this) throws IAE
186 >     * addAll(this) throws IllegalArgumentException
187       */
188      public void testAddAllSelf() {
189 +        LinkedBlockingQueue q = populatedQueue(SIZE);
190          try {
207            LinkedBlockingQueue q = populatedQueue(SIZE);
191              q.addAll(q);
192              shouldThrow();
193 <        }
211 <        catch (IllegalArgumentException success) {}
193 >        } catch (IllegalArgumentException success) {}
194      }
195  
196      /**
215     * addAll of a collection with null elements throws NPE
216     */
217    public void testAddAll2() {
218        try {
219            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
220            Integer[] ints = new Integer[SIZE];
221            q.addAll(Arrays.asList(ints));
222            shouldThrow();
223        }
224        catch (NullPointerException success) {}
225    }
226    /**
197       * addAll of a collection with any null elements throws NPE after
198       * possibly adding some elements
199       */
200      public void testAddAll3() {
201 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
202 +        Integer[] ints = new Integer[SIZE];
203 +        for (int i = 0; i < SIZE-1; ++i)
204 +            ints[i] = new Integer(i);
205 +        Collection<Integer> elements = Arrays.asList(ints);
206          try {
207 <            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
233 <            Integer[] ints = new Integer[SIZE];
234 <            for (int i = 0; i < SIZE-1; ++i)
235 <                ints[i] = new Integer(i);
236 <            q.addAll(Arrays.asList(ints));
207 >            q.addAll(elements);
208              shouldThrow();
209 <        }
239 <        catch (NullPointerException success) {}
209 >        } catch (NullPointerException success) {}
210      }
211 +
212      /**
213 <     * addAll throws ISE if not enough room
213 >     * addAll throws IllegalStateException if not enough room
214       */
215      public void testAddAll4() {
216 +        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE - 1);
217 +        Integer[] ints = new Integer[SIZE];
218 +        for (int i = 0; i < SIZE; ++i)
219 +            ints[i] = new Integer(i);
220 +        Collection<Integer> elements = Arrays.asList(ints);
221          try {
222 <            LinkedBlockingQueue q = new LinkedBlockingQueue(1);
247 <            Integer[] ints = new Integer[SIZE];
248 <            for (int i = 0; i < SIZE; ++i)
249 <                ints[i] = new Integer(i);
250 <            q.addAll(Arrays.asList(ints));
222 >            q.addAll(elements);
223              shouldThrow();
224 <        }
253 <        catch (IllegalStateException success) {}
224 >        } catch (IllegalStateException success) {}
225      }
226 +
227      /**
228       * Queue contains all elements, in traversal order, of successful addAll
229       */
230      public void testAddAll5() {
231 <        try {
232 <            Integer[] empty = new Integer[0];
233 <            Integer[] ints = new Integer[SIZE];
234 <            for (int i = 0; i < SIZE; ++i)
235 <                ints[i] = new Integer(i);
236 <            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
237 <            assertFalse(q.addAll(Arrays.asList(empty)));
238 <            assertTrue(q.addAll(Arrays.asList(ints)));
239 <            for (int i = 0; i < SIZE; ++i)
268 <                assertEquals(ints[i], q.poll());
269 <        }
270 <        finally {}
231 >        Integer[] empty = new Integer[0];
232 >        Integer[] ints = new Integer[SIZE];
233 >        for (int i = 0; i < SIZE; ++i)
234 >            ints[i] = new Integer(i);
235 >        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
236 >        assertFalse(q.addAll(Arrays.asList(empty)));
237 >        assertTrue(q.addAll(Arrays.asList(ints)));
238 >        for (int i = 0; i < SIZE; ++i)
239 >            assertEquals(ints[i], q.poll());
240      }
241  
242      /**
274     * put(null) throws NPE
275     */
276     public void testPutNull() {
277        try {
278            LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
279            q.put(null);
280            shouldThrow();
281        }
282        catch (NullPointerException success) {
283        }
284        catch (InterruptedException ie) {
285            unexpectedException();
286        }
287     }
288
289    /**
243       * all elements successfully put are contained
244       */
245 <     public void testPut() {
246 <         try {
247 <             LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
248 <             for (int i = 0; i < SIZE; ++i) {
249 <                 Integer I = new Integer(i);
250 <                 q.put(I);
298 <                 assertTrue(q.contains(I));
299 <             }
300 <             assertEquals(0, q.remainingCapacity());
301 <         }
302 <        catch (InterruptedException ie) {
303 <            unexpectedException();
245 >    public void testPut() throws InterruptedException {
246 >        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
247 >        for (int i = 0; i < SIZE; ++i) {
248 >            Integer I = new Integer(i);
249 >            q.put(I);
250 >            assertTrue(q.contains(I));
251          }
252 +        assertEquals(0, q.remainingCapacity());
253      }
254  
255      /**
256       * put blocks interruptibly if full
257       */
258 <    public void testBlockingPut() {
259 <        Thread t = new Thread(new Runnable() {
260 <                public void run() {
261 <                    int added = 0;
262 <                    try {
263 <                        LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
264 <                        for (int i = 0; i < SIZE; ++i) {
265 <                            q.put(new Integer(i));
266 <                            ++added;
267 <                        }
268 <                        q.put(new Integer(SIZE));
269 <                        threadShouldThrow();
270 <                    } catch (InterruptedException ie) {
271 <                        threadAssertEquals(added, SIZE);
272 <                    }
273 <                }});
274 <        t.start();
275 <        try {
276 <           Thread.sleep(SHORT_DELAY_MS);
277 <           t.interrupt();
278 <           t.join();
279 <        }
280 <        catch (InterruptedException ie) {
281 <            unexpectedException();
282 <        }
258 >    public void testBlockingPut() throws InterruptedException {
259 >        final LinkedBlockingQueue q = new LinkedBlockingQueue(SIZE);
260 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
261 >        Thread t = newStartedThread(new CheckedRunnable() {
262 >            public void realRun() throws InterruptedException {
263 >                for (int i = 0; i < SIZE; ++i)
264 >                    q.put(i);
265 >                assertEquals(SIZE, q.size());
266 >                assertEquals(0, q.remainingCapacity());
267 >
268 >                Thread.currentThread().interrupt();
269 >                try {
270 >                    q.put(99);
271 >                    shouldThrow();
272 >                } catch (InterruptedException success) {}
273 >                assertFalse(Thread.interrupted());
274 >
275 >                pleaseInterrupt.countDown();
276 >                try {
277 >                    q.put(99);
278 >                    shouldThrow();
279 >                } catch (InterruptedException success) {}
280 >                assertFalse(Thread.interrupted());
281 >            }});
282 >
283 >        await(pleaseInterrupt);
284 >        assertThreadStaysAlive(t);
285 >        t.interrupt();
286 >        awaitTermination(t);
287 >        assertEquals(SIZE, q.size());
288 >        assertEquals(0, q.remainingCapacity());
289      }
290  
291      /**
292 <     * put blocks waiting for take when full
292 >     * put blocks interruptibly waiting for take when full
293       */
294 <    public void testPutWithTake() {
294 >    public void testPutWithTake() throws InterruptedException {
295 >        final int capacity = 2;
296          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
297 <        Thread t = new Thread(new Runnable() {
298 <                public void run() {
299 <                    int added = 0;
300 <                    try {
301 <                        q.put(new Object());
302 <                        ++added;
303 <                        q.put(new Object());
304 <                        ++added;
305 <                        q.put(new Object());
306 <                        ++added;
307 <                        q.put(new Object());
308 <                        ++added;
309 <                        threadShouldThrow();
310 <                    } catch (InterruptedException e) {
311 <                        threadAssertTrue(added >= 2);
312 <                    }
313 <                }
314 <            });
315 <        try {
316 <            t.start();
317 <            Thread.sleep(SHORT_DELAY_MS);
318 <            q.take();
319 <            t.interrupt();
320 <            t.join();
321 <        } catch (Exception e) {
322 <            unexpectedException();
368 <        }
297 >        final CountDownLatch pleaseTake = new CountDownLatch(1);
298 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
299 >        Thread t = newStartedThread(new CheckedRunnable() {
300 >            public void realRun() throws InterruptedException {
301 >                for (int i = 0; i < capacity; i++)
302 >                    q.put(i);
303 >                pleaseTake.countDown();
304 >                q.put(86);
305 >
306 >                pleaseInterrupt.countDown();
307 >                try {
308 >                    q.put(99);
309 >                    shouldThrow();
310 >                } catch (InterruptedException success) {}
311 >                assertFalse(Thread.interrupted());
312 >            }});
313 >
314 >        await(pleaseTake);
315 >        assertEquals(q.remainingCapacity(), 0);
316 >        assertEquals(0, q.take());
317 >
318 >        await(pleaseInterrupt);
319 >        assertThreadStaysAlive(t);
320 >        t.interrupt();
321 >        awaitTermination(t);
322 >        assertEquals(q.remainingCapacity(), 0);
323      }
324  
325      /**
# Line 373 | Line 327 | public class LinkedBlockingQueueTest ext
327       */
328      public void testTimedOffer() {
329          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
330 <        Thread t = new Thread(new Runnable() {
331 <                public void run() {
332 <                    try {
333 <                        q.put(new Object());
334 <                        q.put(new Object());
335 <                        threadAssertFalse(q.offer(new Object(), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
336 <                        q.offer(new Object(), LONG_DELAY_MS, TimeUnit.MILLISECONDS);
337 <                        threadShouldThrow();
338 <                    } catch (InterruptedException success) {}
339 <                }
340 <            });
341 <
342 <        try {
343 <            t.start();
344 <            Thread.sleep(SMALL_DELAY_MS);
345 <            t.interrupt();
346 <            t.join();
347 <        } catch (Exception e) {
348 <            unexpectedException();
395 <        }
330 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
331 >        Thread t = newStartedThread(new CheckedRunnable() {
332 >            public void realRun() throws InterruptedException {
333 >                q.put(new Object());
334 >                q.put(new Object());
335 >                long startTime = System.nanoTime();
336 >                assertFalse(q.offer(new Object(), timeoutMillis(), MILLISECONDS));
337 >                assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
338 >                pleaseInterrupt.countDown();
339 >                try {
340 >                    q.offer(new Object(), 2 * LONG_DELAY_MS, MILLISECONDS);
341 >                    shouldThrow();
342 >                } catch (InterruptedException success) {}
343 >            }});
344 >
345 >        await(pleaseInterrupt);
346 >        assertThreadStaysAlive(t);
347 >        t.interrupt();
348 >        awaitTermination(t);
349      }
350  
351      /**
352       * take retrieves elements in FIFO order
353       */
354 <    public void testTake() {
355 <        try {
356 <            LinkedBlockingQueue q = populatedQueue(SIZE);
357 <            for (int i = 0; i < SIZE; ++i) {
405 <                assertEquals(i, ((Integer)q.take()).intValue());
406 <            }
407 <        } catch (InterruptedException e) {
408 <            unexpectedException();
354 >    public void testTake() throws InterruptedException {
355 >        LinkedBlockingQueue q = populatedQueue(SIZE);
356 >        for (int i = 0; i < SIZE; ++i) {
357 >            assertEquals(i, q.take());
358          }
359      }
360  
361      /**
362 <     * take blocks interruptibly when empty
362 >     * Take removes existing elements until empty, then blocks interruptibly
363       */
364 <    public void testTakeFromEmpty() {
365 <        final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
366 <        Thread t = new Thread(new Runnable() {
367 <                public void run() {
368 <                    try {
369 <                        q.take();
370 <                        threadShouldThrow();
422 <                    } catch (InterruptedException success) { }
364 >    public void testBlockingTake() throws InterruptedException {
365 >        final BlockingQueue q = populatedQueue(SIZE);
366 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
367 >        Thread t = newStartedThread(new CheckedRunnable() {
368 >            public void realRun() throws InterruptedException {
369 >                for (int i = 0; i < SIZE; ++i) {
370 >                    assertEquals(i, q.take());
371                  }
424            });
425        try {
426            t.start();
427            Thread.sleep(SHORT_DELAY_MS);
428            t.interrupt();
429            t.join();
430        } catch (Exception e) {
431            unexpectedException();
432        }
433    }
372  
373 <    /**
374 <     * Take removes existing elements until empty, then blocks interruptibly
375 <     */
376 <    public void testBlockingTake() {
377 <        Thread t = new Thread(new Runnable() {
378 <                public void run() {
441 <                    try {
442 <                        LinkedBlockingQueue q = populatedQueue(SIZE);
443 <                        for (int i = 0; i < SIZE; ++i) {
444 <                            assertEquals(i, ((Integer)q.take()).intValue());
445 <                        }
446 <                        q.take();
447 <                        threadShouldThrow();
448 <                    } catch (InterruptedException success) {
449 <                    }
450 <                }});
451 <        t.start();
452 <        try {
453 <           Thread.sleep(SHORT_DELAY_MS);
454 <           t.interrupt();
455 <           t.join();
456 <        }
457 <        catch (InterruptedException ie) {
458 <            unexpectedException();
459 <        }
460 <    }
373 >                Thread.currentThread().interrupt();
374 >                try {
375 >                    q.take();
376 >                    shouldThrow();
377 >                } catch (InterruptedException success) {}
378 >                assertFalse(Thread.interrupted());
379  
380 +                pleaseInterrupt.countDown();
381 +                try {
382 +                    q.take();
383 +                    shouldThrow();
384 +                } catch (InterruptedException success) {}
385 +                assertFalse(Thread.interrupted());
386 +            }});
387 +
388 +        await(pleaseInterrupt);
389 +        assertThreadStaysAlive(t);
390 +        t.interrupt();
391 +        awaitTermination(t);
392 +    }
393  
394      /**
395       * poll succeeds unless empty
# Line 466 | Line 397 | public class LinkedBlockingQueueTest ext
397      public void testPoll() {
398          LinkedBlockingQueue q = populatedQueue(SIZE);
399          for (int i = 0; i < SIZE; ++i) {
400 <            assertEquals(i, ((Integer)q.poll()).intValue());
400 >            assertEquals(i, q.poll());
401          }
402          assertNull(q.poll());
403      }
404  
405      /**
406 <     * timed pool with zero timeout succeeds when non-empty, else times out
406 >     * timed poll with zero timeout succeeds when non-empty, else times out
407       */
408 <    public void testTimedPoll0() {
409 <        try {
410 <            LinkedBlockingQueue q = populatedQueue(SIZE);
411 <            for (int i = 0; i < SIZE; ++i) {
481 <                assertEquals(i, ((Integer)q.poll(0, TimeUnit.MILLISECONDS)).intValue());
482 <            }
483 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
484 <        } catch (InterruptedException e) {
485 <            unexpectedException();
408 >    public void testTimedPoll0() throws InterruptedException {
409 >        LinkedBlockingQueue q = populatedQueue(SIZE);
410 >        for (int i = 0; i < SIZE; ++i) {
411 >            assertEquals(i, q.poll(0, MILLISECONDS));
412          }
413 +        assertNull(q.poll(0, MILLISECONDS));
414      }
415  
416      /**
417 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
417 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
418       */
419 <    public void testTimedPoll() {
420 <        try {
421 <            LinkedBlockingQueue q = populatedQueue(SIZE);
422 <            for (int i = 0; i < SIZE; ++i) {
423 <                assertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
424 <            }
425 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
426 <        } catch (InterruptedException e) {
427 <            unexpectedException();
428 <        }
419 >    public void testTimedPoll() throws InterruptedException {
420 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
421 >        for (int i = 0; i < SIZE; ++i) {
422 >            long startTime = System.nanoTime();
423 >            assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
424 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
425 >        }
426 >        long startTime = System.nanoTime();
427 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
428 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
429 >        checkEmpty(q);
430      }
431  
432      /**
433       * Interrupted timed poll throws InterruptedException instead of
434       * returning timeout status
435       */
436 <    public void testInterruptedTimedPoll() {
437 <        Thread t = new Thread(new Runnable() {
438 <                public void run() {
439 <                    try {
440 <                        LinkedBlockingQueue q = populatedQueue(SIZE);
441 <                        for (int i = 0; i < SIZE; ++i) {
442 <                            threadAssertEquals(i, ((Integer)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)).intValue());
443 <                        }
444 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
517 <                    } catch (InterruptedException success) {
518 <                    }
519 <                }});
520 <        t.start();
521 <        try {
522 <           Thread.sleep(SHORT_DELAY_MS);
523 <           t.interrupt();
524 <           t.join();
525 <        }
526 <        catch (InterruptedException ie) {
527 <            unexpectedException();
528 <        }
529 <    }
530 <
531 <    /**
532 <     *  timed poll before a delayed offer fails; after offer succeeds;
533 <     *  on interruption throws
534 <     */
535 <    public void testTimedPollWithOffer() {
536 <        final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
537 <        Thread t = new Thread(new Runnable() {
538 <                public void run() {
539 <                    try {
540 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
541 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
542 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
543 <                        threadShouldThrow();
544 <                    } catch (InterruptedException success) { }
436 >    public void testInterruptedTimedPoll() throws InterruptedException {
437 >        final BlockingQueue<Integer> q = populatedQueue(SIZE);
438 >        final CountDownLatch aboutToWait = new CountDownLatch(1);
439 >        Thread t = newStartedThread(new CheckedRunnable() {
440 >            public void realRun() throws InterruptedException {
441 >                for (int i = 0; i < SIZE; ++i) {
442 >                    long t0 = System.nanoTime();
443 >                    assertEquals(i, (int) q.poll(LONG_DELAY_MS, MILLISECONDS));
444 >                    assertTrue(millisElapsedSince(t0) < SMALL_DELAY_MS);
445                  }
446 <            });
447 <        try {
448 <            t.start();
449 <            Thread.sleep(SMALL_DELAY_MS);
450 <            assertTrue(q.offer(zero, SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
451 <            t.interrupt();
452 <            t.join();
453 <        } catch (Exception e) {
454 <            unexpectedException();
455 <        }
446 >                long t0 = System.nanoTime();
447 >                aboutToWait.countDown();
448 >                try {
449 >                    q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
450 >                    shouldThrow();
451 >                } catch (InterruptedException success) {
452 >                    assertTrue(millisElapsedSince(t0) < MEDIUM_DELAY_MS);
453 >                }
454 >            }});
455 >
456 >        aboutToWait.await();
457 >        waitForThreadToEnterWaitState(t, SMALL_DELAY_MS);
458 >        t.interrupt();
459 >        awaitTermination(t, MEDIUM_DELAY_MS);
460 >        checkEmpty(q);
461      }
462  
463      /**
# Line 561 | Line 466 | public class LinkedBlockingQueueTest ext
466      public void testPeek() {
467          LinkedBlockingQueue q = populatedQueue(SIZE);
468          for (int i = 0; i < SIZE; ++i) {
469 <            assertEquals(i, ((Integer)q.peek()).intValue());
470 <            q.poll();
469 >            assertEquals(i, q.peek());
470 >            assertEquals(i, q.poll());
471              assertTrue(q.peek() == null ||
472 <                       i != ((Integer)q.peek()).intValue());
472 >                       !q.peek().equals(i));
473          }
474          assertNull(q.peek());
475      }
# Line 575 | Line 480 | public class LinkedBlockingQueueTest ext
480      public void testElement() {
481          LinkedBlockingQueue q = populatedQueue(SIZE);
482          for (int i = 0; i < SIZE; ++i) {
483 <            assertEquals(i, ((Integer)q.element()).intValue());
484 <            q.poll();
483 >            assertEquals(i, q.element());
484 >            assertEquals(i, q.poll());
485          }
486          try {
487              q.element();
488              shouldThrow();
489 <        }
585 <        catch (NoSuchElementException success) {}
489 >        } catch (NoSuchElementException success) {}
490      }
491  
492      /**
# Line 591 | Line 495 | public class LinkedBlockingQueueTest ext
495      public void testRemove() {
496          LinkedBlockingQueue q = populatedQueue(SIZE);
497          for (int i = 0; i < SIZE; ++i) {
498 <            assertEquals(i, ((Integer)q.remove()).intValue());
498 >            assertEquals(i, q.remove());
499          }
500          try {
501              q.remove();
502              shouldThrow();
503 <        } catch (NoSuchElementException success) {
600 <        }
503 >        } catch (NoSuchElementException success) {}
504      }
505  
506      /**
# Line 606 | Line 509 | public class LinkedBlockingQueueTest ext
509      public void testRemoveElement() {
510          LinkedBlockingQueue q = populatedQueue(SIZE);
511          for (int i = 1; i < SIZE; i+=2) {
512 <            assertTrue(q.remove(new Integer(i)));
512 >            assertTrue(q.contains(i));
513 >            assertTrue(q.remove(i));
514 >            assertFalse(q.contains(i));
515 >            assertTrue(q.contains(i-1));
516          }
517          for (int i = 0; i < SIZE; i+=2) {
518 <            assertTrue(q.remove(new Integer(i)));
519 <            assertFalse(q.remove(new Integer(i+1)));
518 >            assertTrue(q.contains(i));
519 >            assertTrue(q.remove(i));
520 >            assertFalse(q.contains(i));
521 >            assertFalse(q.remove(i+1));
522 >            assertFalse(q.contains(i+1));
523          }
524          assertTrue(q.isEmpty());
525      }
# Line 618 | Line 527 | public class LinkedBlockingQueueTest ext
527      /**
528       * An add following remove(x) succeeds
529       */
530 <    public void testRemoveElementAndAdd() {
531 <        try {
532 <            LinkedBlockingQueue q = new LinkedBlockingQueue();
533 <            assertTrue(q.add(new Integer(1)));
534 <            assertTrue(q.add(new Integer(2)));
535 <            assertTrue(q.remove(new Integer(1)));
536 <            assertTrue(q.remove(new Integer(2)));
537 <            assertTrue(q.add(new Integer(3)));
629 <            assertTrue(q.take() != null);
630 <        } catch (Exception e) {
631 <            unexpectedException();
632 <        }
530 >    public void testRemoveElementAndAdd() throws InterruptedException {
531 >        LinkedBlockingQueue q = new LinkedBlockingQueue();
532 >        assertTrue(q.add(new Integer(1)));
533 >        assertTrue(q.add(new Integer(2)));
534 >        assertTrue(q.remove(new Integer(1)));
535 >        assertTrue(q.remove(new Integer(2)));
536 >        assertTrue(q.add(new Integer(3)));
537 >        assertTrue(q.take() != null);
538      }
539  
540      /**
# Line 710 | Line 615 | public class LinkedBlockingQueueTest ext
615      }
616  
617      /**
618 <     * toArray contains all elements
618 >     * toArray contains all elements in FIFO order
619       */
620      public void testToArray() {
621          LinkedBlockingQueue q = populatedQueue(SIZE);
622          Object[] o = q.toArray();
718        try {
623          for (int i = 0; i < o.length; i++)
624 <            assertEquals(o[i], q.take());
721 <        } catch (InterruptedException e) {
722 <            unexpectedException();
723 <        }
624 >            assertSame(o[i], q.poll());
625      }
626  
627      /**
628 <     * toArray(a) contains all elements
628 >     * toArray(a) contains all elements in FIFO order
629       */
630 <    public void testToArray2() {
631 <        LinkedBlockingQueue q = populatedQueue(SIZE);
630 >    public void testToArray2() throws InterruptedException {
631 >        LinkedBlockingQueue<Integer> q = populatedQueue(SIZE);
632          Integer[] ints = new Integer[SIZE];
633 <        ints = (Integer[])q.toArray(ints);
634 <        try {
635 <            for (int i = 0; i < ints.length; i++)
636 <                assertEquals(ints[i], q.take());
736 <        } catch (InterruptedException e) {
737 <            unexpectedException();
738 <        }
633 >        Integer[] array = q.toArray(ints);
634 >        assertSame(ints, array);
635 >        for (int i = 0; i < ints.length; i++)
636 >            assertSame(ints[i], q.poll());
637      }
638  
639      /**
640 <     * toArray(null) throws NPE
743 <     */
744 <    public void testToArray_BadArg() {
745 <        try {
746 <            LinkedBlockingQueue q = populatedQueue(SIZE);
747 <            Object o[] = q.toArray(null);
748 <            shouldThrow();
749 <        } catch (NullPointerException success) {}
750 <    }
751 <
752 <    /**
753 <     * toArray with incompatible array type throws CCE
640 >     * toArray(incompatible array type) throws ArrayStoreException
641       */
642      public void testToArray1_BadArg() {
643 +        LinkedBlockingQueue q = populatedQueue(SIZE);
644          try {
645 <            LinkedBlockingQueue q = populatedQueue(SIZE);
758 <            Object o[] = q.toArray(new String[10] );
645 >            q.toArray(new String[10]);
646              shouldThrow();
647 <        } catch (ArrayStoreException  success) {}
647 >        } catch (ArrayStoreException success) {}
648      }
649  
763
650      /**
651       * iterator iterates through all elements
652       */
653 <    public void testIterator() {
653 >    public void testIterator() throws InterruptedException {
654          LinkedBlockingQueue q = populatedQueue(SIZE);
655          Iterator it = q.iterator();
656 <        try {
657 <            while (it.hasNext()) {
772 <                assertEquals(it.next(), q.take());
773 <            }
774 <        } catch (InterruptedException e) {
775 <            unexpectedException();
656 >        while (it.hasNext()) {
657 >            assertEquals(it.next(), q.take());
658          }
659      }
660  
661      /**
662       * iterator.remove removes current element
663       */
664 <    public void testIteratorRemove () {
664 >    public void testIteratorRemove() {
665          final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
666          q.add(two);
667          q.add(one);
# Line 790 | Line 672 | public class LinkedBlockingQueueTest ext
672          it.remove();
673  
674          it = q.iterator();
675 <        assertEquals(it.next(), one);
676 <        assertEquals(it.next(), three);
675 >        assertSame(it.next(), one);
676 >        assertSame(it.next(), three);
677          assertFalse(it.hasNext());
678      }
679  
798
680      /**
681       * iterator ordering is FIFO
682       */
# Line 807 | Line 688 | public class LinkedBlockingQueueTest ext
688          assertEquals(0, q.remainingCapacity());
689          int k = 0;
690          for (Iterator it = q.iterator(); it.hasNext();) {
691 <            int i = ((Integer)(it.next())).intValue();
811 <            assertEquals(++k, i);
691 >            assertEquals(++k, it.next());
692          }
693          assertEquals(3, k);
694      }
# Line 816 | Line 696 | public class LinkedBlockingQueueTest ext
696      /**
697       * Modifications do not cause iterators to fail
698       */
699 <    public void testWeaklyConsistentIteration () {
699 >    public void testWeaklyConsistentIteration() {
700          final LinkedBlockingQueue q = new LinkedBlockingQueue(3);
701          q.add(one);
702          q.add(two);
703          q.add(three);
704 <        try {
705 <            for (Iterator it = q.iterator(); it.hasNext();) {
706 <                q.remove();
827 <                it.next();
828 <            }
829 <        }
830 <        catch (ConcurrentModificationException e) {
831 <            unexpectedException();
704 >        for (Iterator it = q.iterator(); it.hasNext();) {
705 >            q.remove();
706 >            it.next();
707          }
708          assertEquals(0, q.size());
709      }
710  
836
711      /**
712       * toString contains toStrings of elements
713       */
# Line 841 | Line 715 | public class LinkedBlockingQueueTest ext
715          LinkedBlockingQueue q = populatedQueue(SIZE);
716          String s = q.toString();
717          for (int i = 0; i < SIZE; ++i) {
718 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
718 >            assertTrue(s.contains(String.valueOf(i)));
719          }
720      }
721  
848
722      /**
723       * offer transfers elements across Executor tasks
724       */
# Line 854 | Line 727 | public class LinkedBlockingQueueTest ext
727          q.add(one);
728          q.add(two);
729          ExecutorService executor = Executors.newFixedThreadPool(2);
730 <        executor.execute(new Runnable() {
731 <            public void run() {
732 <                threadAssertFalse(q.offer(three));
733 <                try {
734 <                    threadAssertTrue(q.offer(three, MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
735 <                    threadAssertEquals(0, q.remainingCapacity());
736 <                }
737 <                catch (InterruptedException e) {
738 <                    threadUnexpectedException();
739 <                }
740 <            }
741 <        });
742 <
743 <        executor.execute(new Runnable() {
871 <            public void run() {
872 <                try {
873 <                    Thread.sleep(SMALL_DELAY_MS);
874 <                    threadAssertEquals(one, q.take());
875 <                }
876 <                catch (InterruptedException e) {
877 <                    threadUnexpectedException();
878 <                }
879 <            }
880 <        });
730 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
731 >        executor.execute(new CheckedRunnable() {
732 >            public void realRun() throws InterruptedException {
733 >                assertFalse(q.offer(three));
734 >                threadsStarted.await();
735 >                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
736 >                assertEquals(0, q.remainingCapacity());
737 >            }});
738 >
739 >        executor.execute(new CheckedRunnable() {
740 >            public void realRun() throws InterruptedException {
741 >                threadsStarted.await();
742 >                assertSame(one, q.take());
743 >            }});
744  
745          joinPool(executor);
746      }
747  
748      /**
749 <     * poll retrieves elements across Executor threads
749 >     * timed poll retrieves elements across Executor threads
750       */
751      public void testPollInExecutor() {
752          final LinkedBlockingQueue q = new LinkedBlockingQueue(2);
753 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
754          ExecutorService executor = Executors.newFixedThreadPool(2);
755 <        executor.execute(new Runnable() {
756 <            public void run() {
757 <                threadAssertNull(q.poll());
758 <                try {
759 <                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
760 <                    threadAssertTrue(q.isEmpty());
761 <                }
762 <                catch (InterruptedException e) {
763 <                    threadUnexpectedException();
764 <                }
765 <            }
766 <        });
767 <
904 <        executor.execute(new Runnable() {
905 <            public void run() {
906 <                try {
907 <                    Thread.sleep(SMALL_DELAY_MS);
908 <                    q.put(one);
909 <                }
910 <                catch (InterruptedException e) {
911 <                    threadUnexpectedException();
912 <                }
913 <            }
914 <        });
755 >        executor.execute(new CheckedRunnable() {
756 >            public void realRun() throws InterruptedException {
757 >                assertNull(q.poll());
758 >                threadsStarted.await();
759 >                assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
760 >                checkEmpty(q);
761 >            }});
762 >
763 >        executor.execute(new CheckedRunnable() {
764 >            public void realRun() throws InterruptedException {
765 >                threadsStarted.await();
766 >                q.put(one);
767 >            }});
768  
769          joinPool(executor);
770      }
# Line 919 | Line 772 | public class LinkedBlockingQueueTest ext
772      /**
773       * A deserialized serialized queue has same elements in same order
774       */
775 <    public void testSerialization() {
776 <        LinkedBlockingQueue q = populatedQueue(SIZE);
777 <
778 <        try {
779 <            ByteArrayOutputStream bout = new ByteArrayOutputStream(10000);
780 <            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
781 <            out.writeObject(q);
782 <            out.close();
783 <
784 <            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
785 <            ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
933 <            LinkedBlockingQueue r = (LinkedBlockingQueue)in.readObject();
934 <            assertEquals(q.size(), r.size());
935 <            while (!q.isEmpty())
936 <                assertEquals(q.remove(), r.remove());
937 <        } catch (Exception e) {
938 <            unexpectedException();
939 <        }
940 <    }
941 <
942 <    /**
943 <     * drainTo(null) throws NPE
944 <     */
945 <    public void testDrainToNull() {
946 <        LinkedBlockingQueue q = populatedQueue(SIZE);
947 <        try {
948 <            q.drainTo(null);
949 <            shouldThrow();
950 <        } catch (NullPointerException success) {
951 <        }
952 <    }
953 <
954 <    /**
955 <     * drainTo(this) throws IAE
956 <     */
957 <    public void testDrainToSelf() {
958 <        LinkedBlockingQueue q = populatedQueue(SIZE);
959 <        try {
960 <            q.drainTo(q);
961 <            shouldThrow();
962 <        } catch (IllegalArgumentException success) {
775 >    public void testSerialization() throws Exception {
776 >        Queue x = populatedQueue(SIZE);
777 >        Queue y = serialClone(x);
778 >
779 >        assertTrue(x != y);
780 >        assertEquals(x.size(), y.size());
781 >        assertEquals(x.toString(), y.toString());
782 >        assertTrue(Arrays.equals(x.toArray(), y.toArray()));
783 >        while (!x.isEmpty()) {
784 >            assertFalse(y.isEmpty());
785 >            assertEquals(x.remove(), y.remove());
786          }
787 +        assertTrue(y.isEmpty());
788      }
789  
790      /**
# Line 990 | Line 814 | public class LinkedBlockingQueueTest ext
814      /**
815       * drainTo empties full queue, unblocking a waiting put.
816       */
817 <    public void testDrainToWithActivePut() {
817 >    public void testDrainToWithActivePut() throws InterruptedException {
818          final LinkedBlockingQueue q = populatedQueue(SIZE);
819 <        Thread t = new Thread(new Runnable() {
820 <                public void run() {
821 <                    try {
822 <                        q.put(new Integer(SIZE+1));
999 <                    } catch (InterruptedException ie) {
1000 <                        threadUnexpectedException();
1001 <                    }
1002 <                }
1003 <            });
1004 <        try {
1005 <            t.start();
1006 <            ArrayList l = new ArrayList();
1007 <            q.drainTo(l);
1008 <            assertTrue(l.size() >= SIZE);
1009 <            for (int i = 0; i < SIZE; ++i)
1010 <                assertEquals(l.get(i), new Integer(i));
1011 <            t.join();
1012 <            assertTrue(q.size() + l.size() >= SIZE);
1013 <        } catch (Exception e) {
1014 <            unexpectedException();
1015 <        }
1016 <    }
1017 <
1018 <    /**
1019 <     * drainTo(null, n) throws NPE
1020 <     */
1021 <    public void testDrainToNullN() {
1022 <        LinkedBlockingQueue q = populatedQueue(SIZE);
1023 <        try {
1024 <            q.drainTo(null, 0);
1025 <            shouldThrow();
1026 <        } catch (NullPointerException success) {
1027 <        }
1028 <    }
819 >        Thread t = new Thread(new CheckedRunnable() {
820 >            public void realRun() throws InterruptedException {
821 >                q.put(new Integer(SIZE+1));
822 >            }});
823  
824 <    /**
825 <     * drainTo(this, n) throws IAE
826 <     */
827 <    public void testDrainToSelfN() {
828 <        LinkedBlockingQueue q = populatedQueue(SIZE);
829 <        try {
830 <            q.drainTo(q, 0);
831 <            shouldThrow();
1038 <        } catch (IllegalArgumentException success) {
1039 <        }
824 >        t.start();
825 >        ArrayList l = new ArrayList();
826 >        q.drainTo(l);
827 >        assertTrue(l.size() >= SIZE);
828 >        for (int i = 0; i < SIZE; ++i)
829 >            assertEquals(l.get(i), new Integer(i));
830 >        t.join();
831 >        assertTrue(q.size() + l.size() >= SIZE);
832      }
833  
834      /**
835 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
835 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
836       */
837      public void testDrainToN() {
838          LinkedBlockingQueue q = new LinkedBlockingQueue();
# Line 1049 | Line 841 | public class LinkedBlockingQueueTest ext
841                  assertTrue(q.offer(new Integer(j)));
842              ArrayList l = new ArrayList();
843              q.drainTo(l, i);
844 <            int k = (i < SIZE)? i : SIZE;
844 >            int k = (i < SIZE) ? i : SIZE;
845              assertEquals(l.size(), k);
846              assertEquals(q.size(), SIZE-k);
847              for (int j = 0; j < k; ++j)

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines