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

Comparing jsr166/src/test/tck/DelayQueueTest.java (file contents):
Revision 1.6 by dl, Sun Oct 5 23:00:40 2003 UTC vs.
Revision 1.53 by jsr166, Mon May 30 22:43:20 2011 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
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/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.*;
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.concurrent.BlockingQueue;
16 > import java.util.concurrent.CountDownLatch;
17 > import java.util.concurrent.Delayed;
18 > import java.util.concurrent.DelayQueue;
19 > import java.util.concurrent.Executors;
20 > import java.util.concurrent.ExecutorService;
21 > import java.util.concurrent.TimeUnit;
22 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
23  
24   public class DelayQueueTest extends JSR166TestCase {
25 +
26 +    public static class Generic extends BlockingQueueTest {
27 +        protected BlockingQueue emptyCollection() {
28 +            return new DelayQueue();
29 +        }
30 +        protected PDelay makeElement(int i) {
31 +            return new PDelay(i);
32 +        }
33 +    }
34 +
35      public static void main(String[] args) {
36 <        junit.textui.TestRunner.run (suite());  
36 >        junit.textui.TestRunner.run(suite());
37      }
38  
39      public static Test suite() {
40 <        return new TestSuite(DelayQueueTest.class);
40 >        return newTestSuite(DelayQueueTest.class,
41 >                            new Generic().testSuite());
42      }
43  
44      private static final int NOCAP = Integer.MAX_VALUE;
45  
46      /**
47 <     * A delayed implmentation for testing.
48 <     * Most  tests use Pseudodelays, where delays are all elapsed
47 >     * A delayed implementation for testing.
48 >     * Most tests use Pseudodelays, where delays are all elapsed
49       * (so, no blocking solely for delays) but are still ordered
50 <     */
51 <    static class PDelay implements Delayed {
50 >     */
51 >    static class PDelay implements Delayed {
52          int pseudodelay;
53          PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
54 <        public int compareTo(Object y) {
54 >        public int compareTo(PDelay y) {
55              int i = pseudodelay;
56 <            int j = ((PDelay)y).pseudodelay;
56 >            int j = y.pseudodelay;
57              if (i < j) return -1;
58              if (i > j) return 1;
59              return 0;
60          }
61  
62 <        public int compareTo(PDelay y) {
63 <            int i = pseudodelay;
41 <            int j = ((PDelay)y).pseudodelay;
42 <            if (i < j) return -1;
43 <            if (i > j) return 1;
44 <            return 0;
62 >        public int compareTo(Delayed y) {
63 >            return compareTo((PDelay)y);
64          }
65  
66          public boolean equals(Object other) {
67 <            return ((PDelay)other).pseudodelay == pseudodelay;
67 >            return equals((PDelay)other);
68          }
69          public boolean equals(PDelay other) {
70 <            return ((PDelay)other).pseudodelay == pseudodelay;
70 >            return other.pseudodelay == pseudodelay;
71          }
72  
54
73          public long getDelay(TimeUnit ignore) {
74              return pseudodelay;
75          }
# Line 64 | Line 82 | public class DelayQueueTest extends JSR1
82          }
83      }
84  
67
85      /**
86       * Delayed implementation that actually delays
87       */
88 <    static class NanoDelay implements Delayed {
88 >    static class NanoDelay implements Delayed {
89          long trigger;
90 <        NanoDelay(long i) {
90 >        NanoDelay(long i) {
91              trigger = System.nanoTime() + i;
92          }
93 <        public int compareTo(Object y) {
93 >        public int compareTo(NanoDelay y) {
94              long i = trigger;
95 <            long j = ((NanoDelay)y).trigger;
95 >            long j = y.trigger;
96              if (i < j) return -1;
97              if (i > j) return 1;
98              return 0;
99          }
100  
101 <        public int compareTo(NanoDelay y) {
102 <            long i = trigger;
86 <            long j = ((NanoDelay)y).trigger;
87 <            if (i < j) return -1;
88 <            if (i > j) return 1;
89 <            return 0;
101 >        public int compareTo(Delayed y) {
102 >            return compareTo((NanoDelay)y);
103          }
104  
105          public boolean equals(Object other) {
106 <            return ((NanoDelay)other).trigger == trigger;
106 >            return equals((NanoDelay)other);
107          }
108          public boolean equals(NanoDelay other) {
109 <            return ((NanoDelay)other).trigger == trigger;
109 >            return other.trigger == trigger;
110          }
111  
112          public long getDelay(TimeUnit unit) {
# Line 110 | Line 123 | public class DelayQueueTest extends JSR1
123          }
124      }
125  
113
126      /**
127       * Create a queue of given size containing consecutive
128       * PDelays 0 ... n.
129       */
130 <    private DelayQueue populatedQueue(int n) {
131 <        DelayQueue q = new DelayQueue();
130 >    private DelayQueue<PDelay> populatedQueue(int n) {
131 >        DelayQueue<PDelay> q = new DelayQueue<PDelay>();
132          assertTrue(q.isEmpty());
133 <        for(int i = n-1; i >= 0; i-=2)
134 <            assertTrue(q.offer(new PDelay(i)));
135 <        for(int i = (n & 1); i < n; i+=2)
136 <            assertTrue(q.offer(new PDelay(i)));
133 >        for (int i = n-1; i >= 0; i-=2)
134 >            assertTrue(q.offer(new PDelay(i)));
135 >        for (int i = (n & 1); i < n; i+=2)
136 >            assertTrue(q.offer(new PDelay(i)));
137          assertFalse(q.isEmpty());
138          assertEquals(NOCAP, q.remainingCapacity());
139 <        assertEquals(n, q.size());
139 >        assertEquals(n, q.size());
140          return q;
141      }
142 <
142 >
143      /**
144       * A new queue has unbounded capacity
145       */
# Line 142 | Line 154 | public class DelayQueueTest extends JSR1
154          try {
155              DelayQueue q = new DelayQueue(null);
156              shouldThrow();
157 <        }
146 <        catch (NullPointerException success) {}
157 >        } catch (NullPointerException success) {}
158      }
159  
160      /**
# Line 154 | Line 165 | public class DelayQueueTest extends JSR1
165              PDelay[] ints = new PDelay[SIZE];
166              DelayQueue q = new DelayQueue(Arrays.asList(ints));
167              shouldThrow();
168 <        }
158 <        catch (NullPointerException success) {}
168 >        } catch (NullPointerException success) {}
169      }
170  
171      /**
# Line 168 | Line 178 | public class DelayQueueTest extends JSR1
178                  ints[i] = new PDelay(i);
179              DelayQueue q = new DelayQueue(Arrays.asList(ints));
180              shouldThrow();
181 <        }
172 <        catch (NullPointerException success) {}
181 >        } catch (NullPointerException success) {}
182      }
183  
184      /**
185       * Queue contains all elements of collection used to initialize
186       */
187      public void testConstructor6() {
188 <        try {
189 <            PDelay[] ints = new PDelay[SIZE];
190 <            for (int i = 0; i < SIZE; ++i)
191 <                ints[i] = new PDelay(i);
192 <            DelayQueue q = new DelayQueue(Arrays.asList(ints));
193 <            for (int i = 0; i < SIZE; ++i)
185 <                assertEquals(ints[i], q.poll());
186 <        }
187 <        finally {}
188 >        PDelay[] ints = new PDelay[SIZE];
189 >        for (int i = 0; i < SIZE; ++i)
190 >            ints[i] = new PDelay(i);
191 >        DelayQueue q = new DelayQueue(Arrays.asList(ints));
192 >        for (int i = 0; i < SIZE; ++i)
193 >            assertEquals(ints[i], q.poll());
194      }
195  
196      /**
# Line 203 | Line 209 | public class DelayQueueTest extends JSR1
209      }
210  
211      /**
212 <     * remainingCapacity does not change when elementa added or removed,
212 >     * remainingCapacity does not change when elements added or removed,
213       * but size does
214       */
215      public void testRemainingCapacity() {
# Line 221 | Line 227 | public class DelayQueueTest extends JSR1
227      }
228  
229      /**
224     * offer(null) throws NPE
225     */
226    public void testOfferNull() {
227        try {
228            DelayQueue q = new DelayQueue();
229            q.offer(null);
230            shouldThrow();
231        } catch (NullPointerException success) { }  
232    }
233
234    /**
235     * add(null) throws NPE
236     */
237    public void testAddNull() {
238        try {
239            DelayQueue q = new DelayQueue();
240            q.add(null);
241            shouldThrow();
242        } catch (NullPointerException success) { }  
243    }
244
245    /**
230       * offer non-null succeeds
231       */
232      public void testOffer() {
# Line 263 | Line 247 | public class DelayQueueTest extends JSR1
247      }
248  
249      /**
266     * addAll(null) throws NPE
267     */
268    public void testAddAll1() {
269        try {
270            DelayQueue q = new DelayQueue();
271            q.addAll(null);
272            shouldThrow();
273        }
274        catch (NullPointerException success) {}
275    }
276
277
278    /**
250       * addAll(this) throws IAE
251       */
252      public void testAddAllSelf() {
# Line 283 | Line 254 | public class DelayQueueTest extends JSR1
254              DelayQueue q = populatedQueue(SIZE);
255              q.addAll(q);
256              shouldThrow();
257 <        }
287 <        catch (IllegalArgumentException success) {}
257 >        } catch (IllegalArgumentException success) {}
258      }
259  
260      /**
291     * addAll of a collection with null elements throws NPE
292     */
293    public void testAddAll2() {
294        try {
295            DelayQueue q = new DelayQueue();
296            PDelay[] ints = new PDelay[SIZE];
297            q.addAll(Arrays.asList(ints));
298            shouldThrow();
299        }
300        catch (NullPointerException success) {}
301    }
302    /**
261       * addAll of a collection with any null elements throws NPE after
262       * possibly adding some elements
263       */
# Line 311 | Line 269 | public class DelayQueueTest extends JSR1
269                  ints[i] = new PDelay(i);
270              q.addAll(Arrays.asList(ints));
271              shouldThrow();
272 <        }
315 <        catch (NullPointerException success) {}
272 >        } catch (NullPointerException success) {}
273      }
274  
275      /**
276       * Queue contains all elements of successful addAll
277       */
278      public void testAddAll5() {
279 <        try {
280 <            PDelay[] empty = new PDelay[0];
281 <            PDelay[] ints = new PDelay[SIZE];
282 <            for (int i = SIZE-1; i >= 0; --i)
283 <                ints[i] = new PDelay(i);
284 <            DelayQueue q = new DelayQueue();
285 <            assertFalse(q.addAll(Arrays.asList(empty)));
286 <            assertTrue(q.addAll(Arrays.asList(ints)));
287 <            for (int i = 0; i < SIZE; ++i)
331 <                assertEquals(ints[i], q.poll());
332 <        }
333 <        finally {}
279 >        PDelay[] empty = new PDelay[0];
280 >        PDelay[] ints = new PDelay[SIZE];
281 >        for (int i = SIZE-1; i >= 0; --i)
282 >            ints[i] = new PDelay(i);
283 >        DelayQueue q = new DelayQueue();
284 >        assertFalse(q.addAll(Arrays.asList(empty)));
285 >        assertTrue(q.addAll(Arrays.asList(ints)));
286 >        for (int i = 0; i < SIZE; ++i)
287 >            assertEquals(ints[i], q.poll());
288      }
289  
290      /**
337     * put(null) throws NPE
338     */
339     public void testPutNull() {
340        try {
341            DelayQueue q = new DelayQueue();
342            q.put(null);
343            shouldThrow();
344        }
345        catch (NullPointerException success){
346        }  
347     }
348
349    /**
291       * all elements successfully put are contained
292       */
293 <     public void testPut() {
294 <         try {
295 <             DelayQueue q = new DelayQueue();
296 <             for (int i = 0; i < SIZE; ++i) {
297 <                 PDelay I = new PDelay(i);
298 <                 q.put(I);
358 <                 assertTrue(q.contains(I));
359 <             }
360 <             assertEquals(SIZE, q.size());
361 <         }
362 <         finally {
293 >    public void testPut() {
294 >        DelayQueue q = new DelayQueue();
295 >        for (int i = 0; i < SIZE; ++i) {
296 >            PDelay I = new PDelay(i);
297 >            q.put(I);
298 >            assertTrue(q.contains(I));
299          }
300 +        assertEquals(SIZE, q.size());
301      }
302  
303      /**
304       * put doesn't block waiting for take
305       */
306 <    public void testPutWithTake() {
306 >    public void testPutWithTake() throws InterruptedException {
307          final DelayQueue q = new DelayQueue();
308 <        Thread t = new Thread(new Runnable() {
309 <                public void run() {
310 <                    int added = 0;
311 <                    try {
312 <                        q.put(new PDelay(0));
313 <                        ++added;
314 <                        q.put(new PDelay(0));
315 <                        ++added;
316 <                        q.put(new PDelay(0));
317 <                        ++added;
381 <                        q.put(new PDelay(0));
382 <                        ++added;
383 <                        threadAssertTrue(added == 4);
384 <                    } finally {
385 <                    }
386 <                }
387 <            });
388 <        try {
389 <            t.start();
390 <            Thread.sleep(SHORT_DELAY_MS);
391 <            q.take();
392 <            t.interrupt();
393 <            t.join();
394 <        } catch (Exception e){
395 <            unexpectedException();
396 <        }
308 >        Thread t = newStartedThread(new CheckedRunnable() {
309 >            public void realRun() {
310 >                q.put(new PDelay(0));
311 >                q.put(new PDelay(0));
312 >                q.put(new PDelay(0));
313 >                q.put(new PDelay(0));
314 >            }});
315 >
316 >        awaitTermination(t);
317 >        assertEquals(4, q.size());
318      }
319  
320      /**
321       * timed offer does not time out
322       */
323 <    public void testTimedOffer() {
323 >    public void testTimedOffer() throws InterruptedException {
324          final DelayQueue q = new DelayQueue();
325 <        Thread t = new Thread(new Runnable() {
326 <                public void run() {
327 <                    try {
328 <                        q.put(new PDelay(0));
329 <                        q.put(new PDelay(0));
330 <                        threadAssertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
331 <                        threadAssertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
411 <                    } finally { }
412 <                }
413 <            });
414 <        
415 <        try {
416 <            t.start();
417 <            Thread.sleep(SMALL_DELAY_MS);
418 <            t.interrupt();
419 <            t.join();
420 <        } catch (Exception e){
421 <            unexpectedException();
422 <        }
423 <    }
325 >        Thread t = newStartedThread(new CheckedRunnable() {
326 >            public void realRun() throws InterruptedException {
327 >                q.put(new PDelay(0));
328 >                q.put(new PDelay(0));
329 >                assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, MILLISECONDS));
330 >                assertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, MILLISECONDS));
331 >            }});
332  
333 <    /**
426 <     * take retrieves elements in priority order
427 <     */
428 <    public void testTake() {
429 <        try {
430 <            DelayQueue q = populatedQueue(SIZE);
431 <            for (int i = 0; i < SIZE; ++i) {
432 <                assertEquals(new PDelay(i), ((PDelay)q.take()));
433 <            }
434 <        } catch (InterruptedException e){
435 <            unexpectedException();
436 <        }  
333 >        awaitTermination(t);
334      }
335  
336      /**
337 <     * take blocks interruptibly when empty
337 >     * take retrieves elements in priority order
338       */
339 <    public void testTakeFromEmpty() {
340 <        final DelayQueue q = new DelayQueue();
341 <        Thread t = new Thread(new Runnable() {
342 <                public void run() {
446 <                    try {
447 <                        q.take();
448 <                        threadShouldThrow();
449 <                    } catch (InterruptedException success){ }                
450 <                }
451 <            });
452 <        try {
453 <            t.start();
454 <            Thread.sleep(SHORT_DELAY_MS);
455 <            t.interrupt();
456 <            t.join();
457 <        } catch (Exception e){
458 <            unexpectedException();
339 >    public void testTake() throws InterruptedException {
340 >        DelayQueue q = populatedQueue(SIZE);
341 >        for (int i = 0; i < SIZE; ++i) {
342 >            assertEquals(new PDelay(i), ((PDelay)q.take()));
343          }
344      }
345  
346      /**
347       * Take removes existing elements until empty, then blocks interruptibly
348       */
349 <    public void testBlockingTake() {
350 <        Thread t = new Thread(new Runnable() {
351 <                public void run() {
352 <                    try {
353 <                        DelayQueue q = populatedQueue(SIZE);
354 <                        for (int i = 0; i < SIZE; ++i) {
355 <                            threadAssertEquals(new PDelay(i), ((PDelay)q.take()));
356 <                        }
473 <                        q.take();
474 <                        threadShouldThrow();
475 <                    } catch (InterruptedException success){
476 <                    }  
477 <                }});
478 <        t.start();
479 <        try {
480 <           Thread.sleep(SHORT_DELAY_MS);
481 <           t.interrupt();
482 <           t.join();
483 <        }
484 <        catch (InterruptedException ie) {
485 <            unexpectedException();
486 <        }
487 <    }
349 >    public void testBlockingTake() throws InterruptedException {
350 >        final DelayQueue q = populatedQueue(SIZE);
351 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
352 >        Thread t = newStartedThread(new CheckedRunnable() {
353 >            public void realRun() throws InterruptedException {
354 >                for (int i = 0; i < SIZE; ++i) {
355 >                    assertEquals(new PDelay(i), ((PDelay)q.take()));
356 >                }
357  
358 +                Thread.currentThread().interrupt();
359 +                try {
360 +                    q.take();
361 +                    shouldThrow();
362 +                } catch (InterruptedException success) {}
363 +                assertFalse(Thread.interrupted());
364 +
365 +                pleaseInterrupt.countDown();
366 +                try {
367 +                    q.take();
368 +                    shouldThrow();
369 +                } catch (InterruptedException success) {}
370 +                assertFalse(Thread.interrupted());
371 +            }});
372 +
373 +        await(pleaseInterrupt);
374 +        assertThreadStaysAlive(t);
375 +        t.interrupt();
376 +        awaitTermination(t);
377 +    }
378  
379      /**
380       * poll succeeds unless empty
# Line 495 | Line 384 | public class DelayQueueTest extends JSR1
384          for (int i = 0; i < SIZE; ++i) {
385              assertEquals(new PDelay(i), ((PDelay)q.poll()));
386          }
387 <        assertNull(q.poll());
387 >        assertNull(q.poll());
388      }
389  
390      /**
391 <     * timed pool with zero timeout succeeds when non-empty, else times out
391 >     * timed poll with zero timeout succeeds when non-empty, else times out
392       */
393 <    public void testTimedPoll0() {
394 <        try {
395 <            DelayQueue q = populatedQueue(SIZE);
396 <            for (int i = 0; i < SIZE; ++i) {
397 <                assertEquals(new PDelay(i), ((PDelay)q.poll(0, TimeUnit.MILLISECONDS)));
398 <            }
510 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
511 <        } catch (InterruptedException e){
512 <            unexpectedException();
513 <        }  
393 >    public void testTimedPoll0() throws InterruptedException {
394 >        DelayQueue q = populatedQueue(SIZE);
395 >        for (int i = 0; i < SIZE; ++i) {
396 >            assertEquals(new PDelay(i), ((PDelay)q.poll(0, MILLISECONDS)));
397 >        }
398 >        assertNull(q.poll(0, MILLISECONDS));
399      }
400  
401      /**
402 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
402 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
403       */
404 <    public void testTimedPoll() {
405 <        try {
406 <            DelayQueue q = populatedQueue(SIZE);
407 <            for (int i = 0; i < SIZE; ++i) {
408 <                assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
409 <            }
410 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
411 <        } catch (InterruptedException e){
412 <            unexpectedException();
413 <        }  
404 >    public void testTimedPoll() throws InterruptedException {
405 >        DelayQueue q = populatedQueue(SIZE);
406 >        for (int i = 0; i < SIZE; ++i) {
407 >            long startTime = System.nanoTime();
408 >            assertEquals(new PDelay(i), ((PDelay)q.poll(LONG_DELAY_MS, MILLISECONDS)));
409 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
410 >        }
411 >        long startTime = System.nanoTime();
412 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
413 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
414 >        checkEmpty(q);
415      }
416  
417      /**
418       * Interrupted timed poll throws InterruptedException instead of
419       * returning timeout status
420       */
421 <    public void testInterruptedTimedPoll() {
422 <        Thread t = new Thread(new Runnable() {
423 <                public void run() {
424 <                    try {
425 <                        DelayQueue q = populatedQueue(SIZE);
426 <                        for (int i = 0; i < SIZE; ++i) {
427 <                            threadAssertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
542 <                        }
543 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
544 <                    } catch (InterruptedException success){
545 <                    }  
546 <                }});
547 <        t.start();
548 <        try {
549 <           Thread.sleep(SHORT_DELAY_MS);
550 <           t.interrupt();
551 <           t.join();
552 <        }
553 <        catch (InterruptedException ie) {
554 <            unexpectedException();
555 <        }
556 <    }
557 <
558 <    /**
559 <     *  timed poll before a delayed offer fails; after offer succeeds;
560 <     *  on interruption throws
561 <     */
562 <    public void testTimedPollWithOffer() {
563 <        final DelayQueue q = new DelayQueue();
564 <        Thread t = new Thread(new Runnable() {
565 <                public void run() {
566 <                    try {
567 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
568 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
569 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
570 <                        threadFail("Should block");
571 <                    } catch (InterruptedException success) { }                
421 >    public void testInterruptedTimedPoll() throws InterruptedException {
422 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
423 >        Thread t = newStartedThread(new CheckedRunnable() {
424 >            public void realRun() throws InterruptedException {
425 >                DelayQueue q = populatedQueue(SIZE);
426 >                for (int i = 0; i < SIZE; ++i) {
427 >                    assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, MILLISECONDS)));
428                  }
573            });
574        try {
575            t.start();
576            Thread.sleep(SMALL_DELAY_MS);
577            assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
578            t.interrupt();
579            t.join();
580        } catch (Exception e){
581            unexpectedException();
582        }
583    }  
429  
430 +                Thread.currentThread().interrupt();
431 +                try {
432 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
433 +                    shouldThrow();
434 +                } catch (InterruptedException success) {}
435 +                assertFalse(Thread.interrupted());
436 +
437 +                pleaseInterrupt.countDown();
438 +                try {
439 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
440 +                    shouldThrow();
441 +                } catch (InterruptedException success) {}
442 +                assertFalse(Thread.interrupted());
443 +            }});
444 +
445 +        await(pleaseInterrupt);
446 +        assertThreadStaysAlive(t);
447 +        t.interrupt();
448 +        awaitTermination(t);
449 +    }
450  
451      /**
452       * peek returns next element, or null if empty
# Line 590 | Line 455 | public class DelayQueueTest extends JSR1
455          DelayQueue q = populatedQueue(SIZE);
456          for (int i = 0; i < SIZE; ++i) {
457              assertEquals(new PDelay(i), ((PDelay)q.peek()));
458 <            q.poll();
459 <            assertTrue(q.peek() == null ||
460 <                       i != ((PDelay)q.peek()).intValue());
458 >            assertEquals(new PDelay(i), ((PDelay)q.poll()));
459 >            if (q.isEmpty())
460 >                assertNull(q.peek());
461 >            else
462 >                assertFalse(new PDelay(i).equals(q.peek()));
463          }
464 <        assertNull(q.peek());
464 >        assertNull(q.peek());
465      }
466  
467      /**
# Line 609 | Line 476 | public class DelayQueueTest extends JSR1
476          try {
477              q.element();
478              shouldThrow();
479 <        }
613 <        catch (NoSuchElementException success) {}
479 >        } catch (NoSuchElementException success) {}
480      }
481  
482      /**
# Line 624 | Line 490 | public class DelayQueueTest extends JSR1
490          try {
491              q.remove();
492              shouldThrow();
493 <        } catch (NoSuchElementException success){
628 <        }  
493 >        } catch (NoSuchElementException success) {}
494      }
495  
496      /**
# Line 642 | Line 507 | public class DelayQueueTest extends JSR1
507          }
508          assertTrue(q.isEmpty());
509      }
510 <        
510 >
511      /**
512       * contains(x) reports true when elements added but not yet removed
513       */
# Line 664 | Line 529 | public class DelayQueueTest extends JSR1
529          assertTrue(q.isEmpty());
530          assertEquals(0, q.size());
531          assertEquals(NOCAP, q.remainingCapacity());
532 <        q.add(new PDelay(1));
532 >        PDelay x = new PDelay(1);
533 >        q.add(x);
534          assertFalse(q.isEmpty());
535 +        assertTrue(q.contains(x));
536          q.clear();
537          assertTrue(q.isEmpty());
538      }
# Line 722 | Line 589 | public class DelayQueueTest extends JSR1
589      /**
590       * toArray contains all elements
591       */
592 <    public void testToArray() {
592 >    public void testToArray() throws InterruptedException {
593          DelayQueue q = populatedQueue(SIZE);
594 <        Object[] o = q.toArray();
594 >        Object[] o = q.toArray();
595          Arrays.sort(o);
596 <        try {
597 <        for(int i = 0; i < o.length; i++)
731 <            assertEquals(o[i], q.take());
732 <        } catch (InterruptedException e){
733 <            unexpectedException();
734 <        }    
596 >        for (int i = 0; i < o.length; i++)
597 >            assertSame(o[i], q.take());
598      }
599  
600      /**
601       * toArray(a) contains all elements
602       */
603      public void testToArray2() {
604 <        DelayQueue q = populatedQueue(SIZE);
605 <        PDelay[] ints = new PDelay[SIZE];
606 <        ints = (PDelay[])q.toArray(ints);
604 >        DelayQueue<PDelay> q = populatedQueue(SIZE);
605 >        PDelay[] ints = new PDelay[SIZE];
606 >        PDelay[] array = q.toArray(ints);
607 >        assertSame(ints, array);
608          Arrays.sort(ints);
609 <        try {
610 <            for(int i = 0; i < ints.length; i++)
747 <                assertEquals(ints[i], q.take());
748 <        } catch (InterruptedException e){
749 <            unexpectedException();
750 <        }    
609 >        for (int i = 0; i < ints.length; i++)
610 >            assertSame(ints[i], q.remove());
611      }
612  
753
613      /**
614 <     * toArray(null) throws NPE
756 <     */
757 <    public void testToArray_BadArg() {
758 <        try {
759 <            DelayQueue q = populatedQueue(SIZE);
760 <            Object o[] = q.toArray(null);
761 <            shouldThrow();
762 <        } catch(NullPointerException success){}
763 <    }
764 <
765 <    /**
766 <     * toArray with incompatable array type throws CCE
614 >     * toArray(incompatible array type) throws ArrayStoreException
615       */
616      public void testToArray1_BadArg() {
617 <        try {
618 <            DelayQueue q = populatedQueue(SIZE);
619 <            Object o[] = q.toArray(new String[10] );
620 <            shouldThrow();
621 <        } catch(ArrayStoreException  success){}
617 >        DelayQueue q = populatedQueue(SIZE);
618 >        try {
619 >            q.toArray(new String[10]);
620 >            shouldThrow();
621 >        } catch (ArrayStoreException success) {}
622      }
623 <    
623 >
624      /**
625       * iterator iterates through all elements
626       */
627      public void testIterator() {
628          DelayQueue q = populatedQueue(SIZE);
629          int i = 0;
630 <        Iterator it = q.iterator();
631 <        while(it.hasNext()) {
630 >        Iterator it = q.iterator();
631 >        while (it.hasNext()) {
632              assertTrue(q.contains(it.next()));
633              ++i;
634          }
# Line 790 | Line 638 | public class DelayQueueTest extends JSR1
638      /**
639       * iterator.remove removes current element
640       */
641 <    public void testIteratorRemove () {
641 >    public void testIteratorRemove() {
642          final DelayQueue q = new DelayQueue();
643          q.add(new PDelay(2));
644          q.add(new PDelay(1));
# Line 804 | Line 652 | public class DelayQueueTest extends JSR1
652          assertFalse(it.hasNext());
653      }
654  
807
655      /**
656       * toString contains toStrings of elements
657       */
# Line 812 | Line 659 | public class DelayQueueTest extends JSR1
659          DelayQueue q = populatedQueue(SIZE);
660          String s = q.toString();
661          for (int i = 0; i < SIZE; ++i) {
662 <            assertTrue(s.indexOf(String.valueOf(Integer.MIN_VALUE+i)) >= 0);
662 >            assertTrue(s.contains(String.valueOf(Integer.MIN_VALUE+i)));
663          }
664 <    }        
664 >    }
665  
666      /**
667 <     * offer transfers elements across Executor tasks
667 >     * timed poll transfers elements across Executor tasks
668       */
669      public void testPollInExecutor() {
670          final DelayQueue q = new DelayQueue();
671 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
672          ExecutorService executor = Executors.newFixedThreadPool(2);
673 <        executor.execute(new Runnable() {
674 <            public void run() {
675 <                threadAssertNull(q.poll());
676 <                try {
677 <                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
678 <                    threadAssertTrue(q.isEmpty());
679 <                }
680 <                catch (InterruptedException e) {
681 <                    threadUnexpectedException();
682 <                }
683 <            }
684 <        });
673 >        executor.execute(new CheckedRunnable() {
674 >            public void realRun() throws InterruptedException {
675 >                assertNull(q.poll());
676 >                threadsStarted.await();
677 >                assertTrue(null != q.poll(LONG_DELAY_MS, MILLISECONDS));
678 >                checkEmpty(q);
679 >            }});
680 >
681 >        executor.execute(new CheckedRunnable() {
682 >            public void realRun() throws InterruptedException {
683 >                threadsStarted.await();
684 >                q.put(new PDelay(1));
685 >            }});
686  
838        executor.execute(new Runnable() {
839            public void run() {
840                try {
841                    Thread.sleep(SHORT_DELAY_MS);
842                    q.put(new PDelay(1));
843                }
844                catch (InterruptedException e) {
845                    threadUnexpectedException();
846                }
847            }
848        });
687          joinPool(executor);
850
688      }
689  
853
690      /**
691 <     * Dekayed actions do not occur until their delay elapses
691 >     * Delayed actions do not occur until their delay elapses
692       */
693 <    public void testDelay() {
694 <        DelayQueue q = new DelayQueue();
695 <        NanoDelay[] elements = new NanoDelay[SIZE];
696 <        for (int i = 0; i < SIZE; ++i) {
697 <            elements[i] = new NanoDelay(1000000000L + 1000000L * (SIZE - i));
698 <        }
699 <        for (int i = 0; i < SIZE; ++i) {
700 <            q.add(elements[i]);
701 <        }
702 <
703 <        try {
704 <            long last = 0;
705 <            for (int i = 0; i < SIZE; ++i) {
870 <                NanoDelay e = (NanoDelay)(q.take());
871 <                long tt = e.getTriggerTime();
872 <                assertTrue(tt <= System.nanoTime());
873 <                if (i != 0)
874 <                    assertTrue(tt >= last);
875 <                last = tt;
876 <            }
877 <        }
878 <        catch(InterruptedException ie) {
879 <            unexpectedException();
693 >    public void testDelay() throws InterruptedException {
694 >        DelayQueue<NanoDelay> q = new DelayQueue<NanoDelay>();
695 >        for (int i = 0; i < SIZE; ++i)
696 >            q.add(new NanoDelay(1000000L * (SIZE - i)));
697 >
698 >        long last = 0;
699 >        for (int i = 0; i < SIZE; ++i) {
700 >            NanoDelay e = q.take();
701 >            long tt = e.getTriggerTime();
702 >            assertTrue(System.nanoTime() - tt >= 0);
703 >            if (i != 0)
704 >                assertTrue(tt >= last);
705 >            last = tt;
706          }
707 +        assertTrue(q.isEmpty());
708      }
709  
710 +    /**
711 +     * peek of a non-empty queue returns non-null even if not expired
712 +     */
713 +    public void testPeekDelayed() {
714 +        DelayQueue q = new DelayQueue();
715 +        q.add(new NanoDelay(Long.MAX_VALUE));
716 +        assertNotNull(q.peek());
717 +    }
718  
719      /**
720 <     * drainTo(null) throws NPE
721 <     */
722 <    public void testDrainToNull() {
723 <        DelayQueue q = populatedQueue(SIZE);
724 <        try {
725 <            q.drainTo(null);
891 <            shouldThrow();
892 <        } catch(NullPointerException success) {
893 <        }
720 >     * poll of a non-empty queue returns null if no expired elements.
721 >     */
722 >    public void testPollDelayed() {
723 >        DelayQueue q = new DelayQueue();
724 >        q.add(new NanoDelay(Long.MAX_VALUE));
725 >        assertNull(q.poll());
726      }
727  
728      /**
729 <     * drainTo(this) throws IAE
730 <     */
731 <    public void testDrainToSelf() {
732 <        DelayQueue q = populatedQueue(SIZE);
733 <        try {
734 <            q.drainTo(q);
903 <            shouldThrow();
904 <        } catch(IllegalArgumentException success) {
905 <        }
729 >     * timed poll of a non-empty queue returns null if no expired elements.
730 >     */
731 >    public void testTimedPollDelayed() throws InterruptedException {
732 >        DelayQueue q = new DelayQueue();
733 >        q.add(new NanoDelay(LONG_DELAY_MS * 1000000L));
734 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
735      }
736  
737      /**
738       * drainTo(c) empties queue into another collection c
739 <     */
739 >     */
740      public void testDrainTo() {
741 <        DelayQueue q = populatedQueue(SIZE);
741 >        DelayQueue q = new DelayQueue();
742 >        PDelay[] elems = new PDelay[SIZE];
743 >        for (int i = 0; i < SIZE; ++i) {
744 >            elems[i] = new PDelay(i);
745 >            q.add(elems[i]);
746 >        }
747          ArrayList l = new ArrayList();
748          q.drainTo(l);
749          assertEquals(q.size(), 0);
750 <        assertEquals(l.size(), SIZE);
750 >        for (int i = 0; i < SIZE; ++i)
751 >            assertEquals(l.get(i), elems[i]);
752 >        q.add(elems[0]);
753 >        q.add(elems[1]);
754 >        assertFalse(q.isEmpty());
755 >        assertTrue(q.contains(elems[0]));
756 >        assertTrue(q.contains(elems[1]));
757 >        l.clear();
758 >        q.drainTo(l);
759 >        assertEquals(q.size(), 0);
760 >        assertEquals(l.size(), 2);
761 >        for (int i = 0; i < 2; ++i)
762 >            assertEquals(l.get(i), elems[i]);
763      }
764  
765      /**
766       * drainTo empties queue
767 <     */
768 <    public void testDrainToWithActivePut() {
767 >     */
768 >    public void testDrainToWithActivePut() throws InterruptedException {
769          final DelayQueue q = populatedQueue(SIZE);
770 <        Thread t = new Thread(new Runnable() {
771 <                public void run() {
772 <                    q.put(new PDelay(SIZE+1));
773 <                }
928 <            });
929 <        try {
930 <            t.start();
931 <            ArrayList l = new ArrayList();
932 <            q.drainTo(l);
933 <            assertTrue(l.size() >= SIZE);
934 <            t.join();
935 <            assertTrue(q.size() + l.size() == SIZE+1);
936 <        } catch(Exception e){
937 <            unexpectedException();
938 <        }
939 <    }
770 >        Thread t = new Thread(new CheckedRunnable() {
771 >            public void realRun() {
772 >                q.put(new PDelay(SIZE+1));
773 >            }});
774  
775 <    /**
776 <     * drainTo(null, n) throws NPE
777 <     */
778 <    public void testDrainToNullN() {
779 <        DelayQueue q = populatedQueue(SIZE);
780 <        try {
947 <            q.drainTo(null, 0);
948 <            shouldThrow();
949 <        } catch(NullPointerException success) {
950 <        }
951 <    }
952 <
953 <    /**
954 <     * drainTo(this, n) throws IAE
955 <     */
956 <    public void testDrainToSelfN() {
957 <        DelayQueue q = populatedQueue(SIZE);
958 <        try {
959 <            q.drainTo(q, 0);
960 <            shouldThrow();
961 <        } catch(IllegalArgumentException success) {
962 <        }
775 >        t.start();
776 >        ArrayList l = new ArrayList();
777 >        q.drainTo(l);
778 >        assertTrue(l.size() >= SIZE);
779 >        t.join();
780 >        assertTrue(q.size() + l.size() >= SIZE);
781      }
782  
783      /**
784 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
785 <     */
784 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
785 >     */
786      public void testDrainToN() {
787          for (int i = 0; i < SIZE + 2; ++i) {
788              DelayQueue q = populatedQueue(SIZE);
789              ArrayList l = new ArrayList();
790              q.drainTo(l, i);
791 <            int k = (i < SIZE)? i : SIZE;
791 >            int k = (i < SIZE) ? i : SIZE;
792              assertEquals(q.size(), SIZE-k);
793              assertEquals(l.size(), k);
794          }
795      }
796  
979
797   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines